【发布时间】: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 的数据类型。这发生在我几乎所有的程序中。
【问题讨论】:
-
l、b和h具有未指定的值,因为您没有初始化它们。所以s的值也是未指定的。在填充这些值之前,您无法计算s。 -
在 c++ 中,当您将表达式分配给变量时,您实际上是在分配该表达式的直接结果。在
s=(l+b+h);之后,变量s具有当时l、b和h的总和。更改任何这些变量都不会追溯更新s。 -
所以...我必须在获得输入后输入 s=(l+b+h) 部分?
-
@ManojVijayakumar 是的,每次它的价值都应该改变。
-
欢迎来到 Stack Overflow!听起来你可以使用good C++ book