c++ - 表达式不可赋值(不使用 * 或 / 的计算器)
问题描述
我必须创建一个计算器,但不使用*
或/
在代码中。我继续得到一个
“表达式不可分配”
尝试使用加法循环进行乘法运算时出错。有什么建议么?
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;
}
解决方案
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
。你的逻辑被否定了
推荐阅读
- reactjs - 无法在 React 中使用 CSS 属性
- php - PHP - 将值插入到特定于 HTML 表中每个用户的数据库中
- git - 如何 git 显示暂存文件?
- cloud - Transit Gateway 是否只允许某些 VPC 位置?
- android - android上CoordinatorLayout中RecyclerView下方的底部视图
- python - 在 Wagtail 中将图像再现设置为中心裁剪
- c# - 具有两个相反 WHERE 条件的左外连接 + 子查询
- sql - 错误:缺少表“fetched_row”的 FROM 子句条目
- django - 如何使用 django 后台任务登录?
- gremlin - 公共顶点的 Gremlin 交点