基本的计算器c++,没有错误,但代码只返回0,不管值是多少
Basic calculator C++, there is no error but code only returns 0 regardless of the value
我对编码相当陌生,经过几周的学习,我想尝试一个基本的计算器,但是这个代码只返回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;
}
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何获取std::result_of函数的返回类型
- QueryWorkingSet总是返回false
- (C++)分析树以计算返回错误值的简单算术表达式
- 访问者访问变体并返回不同类型时出错
- 如何返回一个类的两个对象相加的结果
- OpenInventor从9.8升级到10.4.2后,GLSL纹理返回零
- lower_bound()返回最后一个元素
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 如何取消对nullptr的屏蔽,返回正确的对象
- 奇怪的结构&GCC&clang(void*返回类型)
- 架构决策:返回std::future还是提供回调
- 从python中调用C++函数并获取返回值
- std::find返回vec.end(),而不管值是否在vector中
- 基本的计算器c++,没有错误,但代码只返回0,不管值是多少