x + y == ans;声明无效(C ++)

时间:2015-04-08 21:50:19

标签: c++ console calculator effect

我知道我可以用更有效的方式写一个计算器,但我在最后一步,所以我想完成这个。

警告出现在usleep()

之后

在我的控制台中,我得到0作为我的答案,我得到4个警告说x +, - ,*,/ == ans没有做任何事情。

这可能是一个愚蠢的错误,但是plz haalp。我是C ++和编程的初学者。

#include <iostream>
#include <sstream>
#include <unistd.h>

using namespace std;

int main()
{
    //X is first number, Y is second
    int ans = 0;
    string i;
    int x;
    int y;
    string op;

    cout << "This is a four function integer calculator." << endl << endl << "Type 'help' at any time to view the help screen" << endl<< endl<<"Insert your first number" << endl;
    cin >> i;
    if(i=="help"){
    cout << "Help Menu" << endl << endl << "add = +" << endl <<"subtract = -" << endl <<"multiply = *" << endl <<"divide = /"<< endl;
    cin >> i;
    }else{
    stringstream(i) >> x;
    cout << "Insert your operator" << endl;
    cin >> op;
    cout << "Insert your second number" << endl;
    cin >> y;
    cout << "The calculator will now preform " << x << " " << op << " " << y << endl;
    usleep(1000000);
    if(op== "+"){
        x + y == ans;
        return ans;
    }else if(op=="-"){
        x - y == ans;
        return ans;
    }else if(op=="*"){
        x * y == ans;
        return ans;
    }else if(op=="/"){
        x / y == ans;
        return ans;
    }else{
    cout << "You inserted an illegal operator, please restart the application" << endl;
    }
    cout << endl << ans << endl;
    }
}

1 个答案:

答案 0 :(得分:2)

==是比较运算符。所以用

x + y == ans;

检查x + y是否等于ans,然后丢弃比较结果。这没什么,所以警告。

如果您要将x + y分配给ans,请使用

ans = x + y;

请注意,ans必须位于左侧。