我对编码还很陌生,我想在学习数周后尝试使用基本的计算器,但是,无论输入的数字或函数为多少,此代码仅返回0值。
我不确定自己在做什么错。
#include<iostream>
using namespace std;
int main(){
int number;
int secNumber;
int sum;
string function;
string add;
string subtract;
string divide;
string modulus;
string multiply;
cout << "what will be your first number?" << endl;
cin >> number;
cout << "what will be your second number?" << endl;
cin >> secNumber;
cout << "what would you like to do with these number?" << endl;
cin >> function;
if (function==add)
sum = number + secNumber;
else if (function==subtract)
sum = number - secNumber;
else if(function== divide)
sum = number/secNumber;
else if(function== multiply)
sum = number*secNumber;
else if(function==modulus)
sum = number%secNumber;
cout << "Your sum is "<<sum << endl;
return sum;
}
最佳答案
您没有初始化add
,subtract
等。这些string
都是空的。因此,无论您要输入什么函数,它们都不会将相等值与空字符串进行比较。
相反,请与字符串文字进行比较:
if (function == "add") {
sum = number + secNumber;
}
else if (function == "subtract") {
...
}
...
如果用户输入的功能无效,则在末尾添加错误消息也将很有帮助:
else {
std::cout << "Unknown function " << function;
}