-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のデータ型を変更しようとしましたあまりにも。これは私のほとんどすべてのプログラムで起こります。別の3つのint変数の合計の値でint変数を宣言しました。この変数を印刷すると、大きな負の数が表示されます
'L'、 'B'を設定した後に値を計算すると、 'h'はあなたがそれらを初期化しなかったので、不特定の値を持っています。したがって 's'の値も指定されていません。これらの値を設定するまで、 's'を計算することはできません。 – CoryKramer
C++では、式に変数を代入すると、実際にその式の直接の結果が代入されます。 's =(l + b + h);の後、変数' s'はその時に '' l'、 'b'と' h'のいずれかの和を持っています。これらの変数を変更しても、 's'は遡及的に更新されません。 –
そう...入力を取得した後にs =(l + b + h)の部分を入力する必要がありますか? –