【问题标题】:I declared an int variable with the value of the sum of another 3 int variables. when i print this variable, it shows a huge negative number我用另外 3 个 int 变量之和的值声明了一个 int 变量。当我打印这个变量时,它显示一个巨大的负数
【发布时间】:2017-09-05 16:54:04
【问题描述】:
#include <iostream>
#include <math.h>

using namespace std;

int main()
{
    int l,b,h;
    int s;
    s=(l+b+h);
    float ar=s*(s-l)*(s-b)*(s-h);
    float area;
    int ch;
    cout<<"How do you want to calculate the area?"<<endl;
    cout<<"1) simple formula"<<endl<<"2) heron's formula"<<endl;
    cin>>ch;
    if(ch==1){
        cout<<"Enter the sides of the triangle."<<endl;
        cin>>l>>b>>h;
        area=0.5*(b*h);
        cout<<"Area of the triangle is = "<<area<<endl;
    }
    else if (ch==2){
        cout<<"Enter the sides of the triangle."<<endl;
        cin>>l>>b>>h;
        cout<<s<<endl<<l+b+h<<endl;
        cout<<"The calculated area of the triangle is = "<<sqrt(ar)<<endl;
    }
    return 0;
}

它打印 l+b+h 的正确值,但是对于 s,它显示一个巨大的负数。我也尝试过更改 s 的数据类型。这发生在我几乎所有的程序中。

【问题讨论】:

  • lbh 具有未指定的值,因为您没有初始化它们。所以s 的值也是未指定的。在填充这些值之前,您无法计算 s
  • 在 c++ 中,当您将表达式分配给变量时,您实际上是在分配该表达式的直接结果。在s=(l+b+h); 之后,变量s 具有当时lbh 的总和。更改任何这些变量都不会追溯更新s
  • 所以...我必须在获得输入后输入 s=(l+b+h) 部分?
  • @ManojVijayakumar 是的,每次它的价值都应该改变。
  • 欢迎来到 Stack Overflow!听起来你可以使用good C++ book

标签: c++ sum int


【解决方案1】:

s 计算一次(通过读取未初始化的值,因此是 UB)。

您可以改为创建 lambda:

auto s = [&](){ return l + b + h; };
auto ar = [&](){ return s() * (s() - l) * (s() - b) * (s() - h); };

然后

cout << "Enter the sides of the triangle." << endl;
cin >> l >> b >> h;
cout << s << endl << l + b + h << endl;
cout << "The calculated area of the triangle is = " << sqrt(ar) << endl;

或者在设置值后简单地计算值

cout << "Enter the sides of the triangle." << endl;
cin >> l >> b >> h;
const int s = l + b + h;
const int ar = s * (s - l) * (s - b) * (s - h);

cout << s << endl << l + b + h << endl;
cout << "The calculated area of the triangle is = " << sqrt(ar) << endl;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多