基本的计算器c++,没有错误,但代码只返回0,不管值是多少

Basic calculator C++, there is no error but code only returns 0 regardless of the value

本文关键字:返回 不管 多少 代码 计算器 c++ 有错误      更新时间:2023-10-16

我对编码相当陌生,经过几周的学习,我想尝试一个基本的计算器,但是这个代码只返回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;
}