From 09e4f9d6b77c12f9925c0e7b049d83129d3a3d5f Mon Sep 17 00:00:00 2001 From: Enrico Schellenberger Date: Sat, 3 Feb 2024 17:40:32 +0100 Subject: [PATCH] changed BasicMode.c to priorities operators --- src/main/c/BasicMode.c | 62 ++++++++++++++++++++---------------------- 1 file changed, 30 insertions(+), 32 deletions(-) diff --git a/src/main/c/BasicMode.c b/src/main/c/BasicMode.c index 396440f..f68a11a 100644 --- a/src/main/c/BasicMode.c +++ b/src/main/c/BasicMode.c @@ -10,7 +10,7 @@ void BasicMode() { char endtmp = '0'; //0 false, 1 true double result = 0; double numbers[100] = {0.0}; - char operatoren[100]; + char operators[100]; do { //100 doubles in this array goes through the for loop till 100 numbers or = is entered @@ -19,38 +19,36 @@ void BasicMode() { numbers[i] = testForNumber(); //gets number printf("Enter a operation: "); - operator[i] = testForOperator(); //gets operator - - if (i > 1) { //if function to prevent numbers[-1] - switch (operator[i]) //checks of the operator and switches to the case with the needed function - { - case '+': - result += add(numbers[i - 1], numbers[i]) - break; - - case '-': - result += minus(numbers[i - 1], numbers[i]) - break; - - case '*': - result += multiply(numbers[i - 1], numbers[i]) - break; - - case '/': - result += divide(numbers[i - 1], numbers[i]) - break; - - case '=': - printf("The result is: %d", result); - endtmp = 1; - break; - - default: - break; - } - } - i++; + operators[i] = testForOperator(); //gets operator } } while (endtmp != '1') + + for (int i = 0; i < 100) {//checks all operators to check for priority + if ((operators[i] == '/' || operators[i] == '*') && i > 1) { //if operators[i] == / or * and i>1 so you dont get numbers[-1] + if (operators[i] == '/') { + result += divide(numbers[i - 1], numbers[i]); //divides if char is / and adds number to the result + } + // for all calculations we take the number and the number before that + else { // and do the operation + result += multiply(numbers[i - 1], numbers[i]); //multiplys if char is * and adds number to the result + } + } + + else if ((operators[i] == '+' || operators[i] == '-') && i > 1) { + if (operators[i] == '+') { + result += add(numbers[i - 1], numbers[i]); //adds if char is + and adds number to the result + } + + else { + result += minus(numbers[i - 1], numbers[i]); //subtrakts if char is - and adds number to the result + } + } + + else if (i<=1 && operator[i] == '=') { //if there are less then 2 numbers in the array + result = numbers[i]; //set result to the 0 digit + } + i++; + } + printf("The result is: %d", result); }