我对编码很新,我想在学习数周之后尝试一个基本的计算器,但是这个代码只返回值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;
}
答案 0 :(得分:3)
您未初始化You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.
,add
等。这些subtract
都是空的。因此,无论您输入什么功能,他们都不会与空字符串进行比较。
相反,与字符串文字进行比较:
string
如果用户输入无效函数,最后添加错误消息也会有所帮助:
if (function == "add") {
sum = number + secNumber;
}
else if (function == "subtract") {
...
}
...