You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写简易计算器时所有if/else语句均报‘lvalue required as left operand of assignment’错误,求问题排查

你的简易计算器错误分析与修复方案

嘿,我来帮你搞定这个问题!你的代码里有两个核心错误,直接导致了那个lvalue required as left operand of assignment编译错误,咱们拆解来看:

错误1:赋值语句方向完全搞反了

C++里的赋值规则是把右边的计算结果赋给左边的变量,而你写的是反过来的:

num1 + num2 = sol; // 错误写法:试图给临时计算结果赋值

num1 + num2是一个临时的计算结果(属于「右值」),它不能被赋值,只有变量(「左值」)才能放在赋值符号的左边。正确的写法应该是:

sol = num1 + num2; // 正确:把计算结果存到sol变量里

其他-、*、/分支的赋值语句都要改成这个方向。

错误2:运算符号的变量类型用错了

你声明的bool sign只能存储true或false,但你要读取的是+、-这类字符,完全不匹配!应该把sign的类型改成char,这样才能正确接收和判断输入的运算符号:

char sign; // 替换原来的bool sign

修正后的完整代码

#include <iostream>
using namespace std;
int main() {
    // 声明变量
    int num1;
    int num2;
    int sol;
    char sign; // 修正类型为char
    // 提示输入第一个数字
    cout << "Greetings! Please enter a number." << endl;
    cin >> num1;
    // 提示输入第二个数字
    cout << "Great! Now, please enter the second number." << endl;
    cin >> num2;
    // 提示输入运算符号
    cout << "Almost there! Now, please enter the sign you wish to use in the equation." << endl;
    cin >> sign;
    // 运算逻辑
    if (sign == '+') {
        sol = num1 + num2; // 修正赋值方向
    } else if (sign == '-') {
        sol = num1 - num2;
    } else if (sign == '*') {
        sol = num1 * num2;
    } else if (sign == '/') {
        sol = num1 / num2;
    } else {
        cout << "Sorry, that is not a valid symbol." << endl;
        return 0;
    }
    // 输出结果
    cout << "The solution is: " << sol << endl;
    return 0;
}

补充说明那个错误提示

error: lvalue required as left operand of assignment翻译成大白话就是:「赋值操作的左边得是一个能被赋值的变量(左值),你现在放的是一个不能被赋值的临时结果(右值)」,这就是你把赋值方向搞反后编译器给你的提示~

内容的提问来源于stack exchange,提问作者Chase

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 11:37:35