-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變量。當我打印這個變量時,它顯示一個巨大的負數
'l','B'後簡單地計算出的值, 'h'有未指定的值,因爲你沒有初始化它們。所以's'的值也沒有說明。在填充這些值之前,您無法計算's'。 – CoryKramer
在C++中,當你將一個表達式賦值給一個變量時,你實際上是在分配該表達式的直接結果。在s =(l + b + h)之後;'變量's'具有當時'l','b'和'h'的任何和。改變任何這些變量不會追溯更新's'。 –
所以...我得在輸入後輸入s =(l + b + h)部分? –