"Primitive Calculator" - 创建除法循环时出现问题
"Primitive Calculator" - Problem with creating division loop
我正在尝试创建一个使用循环而不是"*"或"/"运算符的计算器。我在下面的除法循环中计算结果时遇到问题,该除法循环将两个正数作为输入。如何计算准确的结果?
cout << "Enter the expression to run the calculaor simulator: " << endl;
cin >> lhs >> op >> rhs;
// lhs and rhs stand for left/right hand side of the input expression
// op is the operator (+,-,*,/)
case'*':
{
result = 0;
for(i = 1; i <= rhs; i++)
{
result = result + lhs;
}
cout << "The result is " << result;
break;
}
// So this is my working multiplication part
// Now i have to somehow do the subtraction form for division
case'/':
{
result = lhs;
for (i = 1; result > 0 && result > rhs;i++)
{
result = result - rhs;
}
// This is the loop which is giving me a hard time
// I was gonna leave this blank because nothing I've been doing seems to be working but
// I wanted you to get a general idea of what I was thinking
}
cout << "The result is " << i << endl;
// I print out i from the count to see how many times the number gets divided
你几乎计算结果中的余数,而除法几乎在 i
正值的正确方法是:
#include <iostream>
using namespace std;
int main()
{
int lhs, rhs;
if (!(cin >> lhs >> rhs))
cerr << "invalid inputs" << endl;
else if (rhs == 0)
cerr << "divide by 0";
else {
int result = 0;
while (lhs >= rhs) {
lhs -= rhs;
result += 1;
}
cout << "div = " << result << " (remainder = " << lhs << ')' << endl;
}
}
编译和执行:
/tmp % g++ -pedantic -Wall -Wextra d.cc
/tmp % ./a.out
11 5
div = 2 (remainder = 1)
/tmp % ./a.out
3 3
div = 1 (remainder = 0)
/tmp % ./a.out
2 3
div = 0 (remainder = 2)
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 在java中解决这段代码时面临循环中的问题
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 在 for 循环中查找问题时遇到困难
- 嵌套for循环C++的问题(初学者)
- 退出简单while循环时出现问题
- 循环无限运行C++解决骑士之旅问题
- Visual Studio 2017循环自动向量化问题
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 嵌套While循环不起作用(C++问题)
- 使用 GMP 的 while 循环出现问题
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- OpenMP for 循环并行性问题
- 这个返回元素位置的基于循环的函数有什么问题?
- 为什么循环会导致指针出现问题?
- 使用基于范围的循环迭代矢量时出现问题
- 在 c++ 中循环遍历数组时遇到问题
- 运行无限循环的最小二叉树问题
- 在C++中循环访问自定义结构列表的小问题
- 在 for 循环中更新两个变量时遇到问题C++