首页 > 解决方案 > 表达式不可赋值(不使用 * 或 / 的计算器)

问题描述

我必须创建一个计算器,但不使用*/在代码中。我继续得到一个

“表达式不可分配”

尝试使用加法循环进行乘法运算时出错。有什么建议么?

char op;
int lhs, rhs; // stands for left-hand and right hand side of user input expression
int i;
int lhsnew;
int lhs2;

cout << "Enter the expression to run the calculator simulator: " << endl;
cin >> lhs >> op >> rhs;
//left hand side(lhs) operator right hand side (rhs)

switch(op)
// Switch based on operator chosen by user
{
    case'+':
    {
        cout << "The result is " << lhs + rhs << endl;
        break;
    }
    case'-':
    {
        cout << "The result is " << lhs - rhs << endl;
        break;
    }
    case'*':
    {
    // Here I made the loop control variable same as the rhs number submitted by user
        while(i >= rhs)
        {
            lhsnew = 0;
            lhsnew + lhs = lhsnew;

            i++;
            // Should I use a different looping method?
        }
        cout << "The result is " << lhsnew;`enter code here`
        break;
    }

    // Haven't included case for division
    return 0;
}

标签: c++

解决方案


lhsnew + lhs = lhsnew;

应该

lhsnew = lhsnew + lhs;

我猜你只是把它弄反了。但是那你为什么写正确

lhsnew = 0;

而不是不正确的

0 = lhsnew;

在 C++ 中,您分配的内容位于右侧,而您分配的内容(通常是变量)位于左侧。

另请注意,您的循环非常错误,应该是

    lhsnew = 0;
    i = 0;
    while (i < rhs)
    {
        lhsnew = lhsnew + lhs;
        i++;
    }

1)您只想将零分配给lhsnew一次,因此它应该在循环之前,而不是在循环内部。

2)你i在使用它之前从来没有给过一个值,它需要从零开始

3)你想继续循环 while i < rhs,而不是 while i >= rhs。你的逻辑被否定了


推荐阅读