2017-09-05 53 views
-4
#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的数据类型太。这几乎发生在我所有的程序中。我用另外3个int变量之和的值声明了一个int变量。当我打印这个变量时,它显示一个巨大的负数

+4

'l','B'后简单地计算出的值, 'h'有未指定的值,因为你没有初始化它们。所以's'的值也没有说明。在填充这些值之前,您无法计算's'。 – CoryKramer

+2

在C++中,当你将一个表达式赋值给一个变量时,你实际上是在分配该表达式的直接结果。在s =(l + b + h)之后;'变量's'具有当时'l','b'和'h'的任何和。改变任何这些变量不会追溯更新's'。 –

+0

所以...我得在输入后输入s =(l + b + h)部分? –

回答

0

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

您可以改为创建拉姆达:

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; 
相关问题