以下程序在计算选择后终止,没有任何进一步发生。所以我的问题是我在做什么?请有人检查这个程序并通知我我的错误。该程序是一个计算器,要求用户选择计算方法,即加法,除法或乘法等,然后在计算后显示结果 图片:http://i43.tinypic.com/2hykpjp.png 请原谅我,因为我是C编程的新手。
main()
{
// declaration
int add,sub,mul,div,selection;
float a,b,c;
// prompt user to select a method
cout << "Calculator, which performs addition,subtraction,multiplication and division: add,sub,mul,div";
cout << "Please enter your selection (for example: mul): ";
cin >> selection;
if (selection = add)
{
// prompt user to enter values
cout << "Please enter first value: ";
cin >> a;
cout << "Please enter second value: ";
cin >> b;
// calculations
c = a + b;
// result
cout << "Answer: " << c;
}
if (selection == sub)
{
// prompt user to enter values
cout << "Please enter first value: ";
cin >> a;
cout << "Please enter second value: ";
cin >> b;
// calculations
c = a - b;
// result
cout << "Answer: " << c;
}
if (selection == mul)
{
// prompt user to enter values
cout << "Please enter first value: ";
cin >> a;
cout << "Please enter second value: ";
cin >> b;
// calculations
c = a * b;
// result
cout << "Answer: " << c;
}
if (selection == div)
{
// prompt user to enter values
cout << "Please enter first value: ";
cin >> a;
cout << "Please enter second value: ";
cin >> b;
// calculations
c = a / b;
// result
cout << "Answer: " << c;
}
}
答案 0 :(得分:2)
您尚未在此处初始化任何内容:
int add,sub,mul,div,selection;
您使用selection
获取cin >> selection;
的值,但这些内容应该是什么意思:
if (selection = add)
if (selection == sub)
if (selection == mul)
if (selection == div)
存储类auto
的变量未初始化为任何默认值。
答案 1 :(得分:1)
以下行没有初始化。
int add,sub,mul,div,selection;
使用唯一值初始化这些变量(例如0表示添加,1表示sub)。 另外,相比之下
selection = add
使用
selection == add
使用else if
代替ifs。它将改善性能。在您的情况下,它将比较每个条件。它显示为一个例子。
if (selection = add)
{
// prompt user to enter values
cout << "Please enter first value: ";
cin >> a;
cout << "Please enter second value: ";
cin >> b;
// calculations
c = a + b;
// result
cout << "Answer: " << c;
}
else if (selection == sub)
{
// prompt user to enter values
cout << "Please enter first value: ";
cin >> a;
cout << "Please enter second value: ";
cin >> b;
// calculations
c = a - b;
// result
cout << "Answer: " << c;
}
//Rest of your program.
答案 2 :(得分:1)
根据您运行程序的示例,您要做的是输入字符串,例如添加,然后比较它们。你在程序中实际做的是选择,添加, sub 等等是整数变量,它们只能用于存储整数。
您必须将选择声明为字符串变量,并将其值与字符串常量进行比较,如下所示:
string selection;
然后:
if (selection == "add")