c++ - “原始计算器” - 创建除法循环的问题
问题描述
我正在尝试创建一个使用循环而不是“*”或“/”运算符的计算器。我在计算下面的除法循环中的结果时遇到问题,该循环将两个正数作为输入。我怎样才能计算出准确的结果?
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)
推荐阅读
- java - JavaFX - TextFlow 中的下标和上标文本
- javascript - 使用 jquery 或 javascript 将加载事件附加到 iframe 中的图像
- c++ - 创建类型列表并访问每种类型的静态成员?
- c - 对于某些输入,C 程序突然结束
- ruby-on-rails - 在 Rails activerecord 搜索中查找确切的子字符串
- sql - PostgreSQL 查询组由两个“参数”
- ansible - 无法打开会话错误
- xamarin.forms - 如何填充stacklayout中的可用空间?
- php - 查找 user2 的好友 + 与 user1 的相互计数
- r - 插入符号交叉验证中的预处理