«Примитивный калькулятор» - проблема с созданием цикла деления - PullRequest
0 голосов
/ 22 марта 2019

Я пытаюсь создать калькулятор, который использует циклы вместо операторов '*' или '/'. У меня проблемы с вычислением результата в рамках моего цикла деления, который принимает в качестве входных данных два положительных числа. Как я могу вычислить точный результат?

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

1 Ответ

2 голосов
/ 22 марта 2019

Вы почти вычислите остаток в результат , в то время как деление составляет почти в 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)
...