mardi 6 novembre 2018

C++ Digital Calculator Simulator

I'm currently stuck on having to write a simulator for a real, old calculator (like those one dollar calculators, the ones with the buttons, in which you must enter your numbers one push-of-a-button at a time, can't write the Whole number directly and for now it is only in integers). I know for sure that there has to be a switch case for the 0-9 and one for the operators (including '='). Should break the cycle and print the result of the calculation, but I can use as many operators as I want in the each "session" (ex: 123+7-89/6*8+3). I am finding trouble in connecting the two loops and in printing the result. Thank you so much in advance.

#include <iostream>
using namespace std;

int execute(int n1, int n2, char c);

int main()
{
int acc, num=0;
char c, op;
cin>>c;
while (1) {
    switch (c) {
        case '0': cout << "0";
        case '1': cout << "1";
        case '2': cout << "2";
        case '3': cout << "3";
        case '4': cout << "4";
        case '5': cout << "5";
        case '6': cout << "6";
        case '7': cout << "7";
        case '8': cout << "8";
        case '9': cout << "9";
        num=num*10+static_cast<int>(c-'0');
        acc=num;
        op=c;
        acc= execute(acc, num, op);
    }
}

return 0;
}

int execute(int n1, int n2, char c) {
do {
    switch (c) {
        case '+': return (n1+n2);
        case '-': return (n1-n2);
        case '*': return (n1*n2);
        case '/': return (n1/n2);
        case '=': return true;
    }
} while (!'=')
}

Aucun commentaire:

Enregistrer un commentaire