[英]“Primitive Calculator” - Problem with creating division loop
I am trying to create a calculator that uses loops instead of the '*' or '/' operators. 我正在尝试创建一个使用循环而不是'*'或'/'运算符的计算器。 I am having problems in computing the result within my division loop below that takes in two positive numbers as input.
我在下面的除法循环中计算结果时遇到问题,该结果将两个正数作为输入。 How can I compute the accurate result?
如何计算准确的结果?
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
you almost compute the remainder in result while the division is almost in i 当除数几乎在i中时,您几乎计算出结果的余数
A correct way for positive values can be : 正值的正确方法可以是:
#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;
}
}
Compilation and execution : 编译执行:
/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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.