我是C ++的新手,我无法解决为什么代码会在用户输入RecPrisim,TriPrisim或Cylinder时停止,程序停止,打印出一些随机数并关闭。我只是想知道它是否因为变量需要数字而我尝试使用字符串做同样的事情而且我得到了错误。
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
using namespace std;
int main()
{
int Length;
int Height;
int Base;
int Width;
int UserChoice;
int ObjectResult;
int RecPrisim;
int TriPrisim;
int Cylinder;
int TriResulta;
RecPrisim = 1;
TriPrisim = 1;
Cylinder = 1;
TriResulta = 1;
cout << "Choose one: RecPrisim, TriPrisim or Cylinder." << endl;
cin >> UserChoice;
if (UserChoice = RecPrisim)
{
cout << "Enter Length, Width then Height.";
cin >> Length;
cin >> Width;
cin >> Height;
ObjectResult = Length*Width*Height;
cout << ObjectResult;
}
else if (UserChoice = TriPrisim)
{
cout << "Enter Base, Height, Width, Length." << endl;
cin >> Base;
cin >> Height;
cin >> Width;
cin >> Length;
ObjectResult = Base*Height / 2 * Width*Length;
cout << ObjectResult;
}
else if (UserChoice = Cylinder)
{
cout << "Enter Radius and Length." << endl;
cin >> Base;
cin >> Height;
ObjectResult = 3.1459*Base*Base*Height;
cout << ObjectResult;
}
system("pause");
}
答案 0 :(得分:4)
使用==
代替=
。
在C ++中,C和更多语言==
用于比较值,而=
用于分配值。
如果您想要使用值test
初始化变量val
,那么您应该使用test = val
。
但是在if
条件下,您(通常)希望使用比较运算符(如下面的
==
用于比较LHS是否等于RHS >
用于比较LHS是否大于RHS <
用于比较LHS是否小于RHS 根据值,运算符将返回true
或false
,并且if
条件将被执行。
因为在您的情况下,您希望将UserChoice
的值与其他值相等进行比较,您应该使用==
代替=
。
答案 1 :(得分:1)
请使用==
,而不是=
。例如,
无论a的值是什么,代码if(a = 1)
都将始终为真,因为if(1)
始终为真。只有代码if(a == 1)
才是你想要的。我希望这可以帮到你。