2017-09-05 51 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; 
相關問題