C++ 我声明了一个int变量,它的值是另外3个int变量的和。当我打印这个变量时,它会显示一个巨大的负数 #包括 #包括 使用名称空间std; int main() { int l,b,h; int-s; s=(l+b+h); 浮动ar=s*(s-l)*(s-b)*(s-h); 漂浮区; int-ch; cout
C++ 我声明了一个int变量,它的值是另外3个int变量的和。当我打印这个变量时,它会显示一个巨大的负数 #包括 #包括 使用名称空间std; int main() { int l,b,h; int-s; s=(l+b+h); 浮动ar=s*(s-l)*(s-b)*(s-h); 漂浮区; int-ch; cout,c++,sum,int,C++,Sum,Int,s计算一次(通过读取未初始化的值,所以UB) 您可以改为创建lambda: #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
s
计算一次(通过读取未初始化的值,所以UB)
您可以改为创建lambda:
#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;
}
然后
auto s = [&](){ return l + b + h; };
auto ar = [&](){ return s() * (s() - l) * (s() - b) * (s() - h); };
coutl>>b>>h;
CUT<代码> L>代码>代码> B<代码>和<代码> H/CODE>由于未初始化它们,所以有未指定的值。因此,<>代码> s>代码>的值也未指定。在填充这些值之后,不能计算<代码> s >代码>。在C++中,当将表达式赋值给变量时,实际上是赋值的结果。表达式。在s=(l+b+h);
之后,变量s
具有l
、b
和h
当时的总和。更改这些变量中的任何一个都不会追溯更新s
。因此……我必须键入s=(l+b+h)获取输入后的部分?@ManojVijayakumar是的,每次它的值都应该改变。欢迎使用堆栈溢出!听起来你可以使用
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;