Dan_yef Dan_yef - 3 months ago 20
C Question

Calculator(accumulator) in c programming language

I want to programm the basic calculator in c:
I have the problem with accumulator(with "+" and "-" operators)

int main(void)
{
float num1,num2,res;
char operator;

printf ("Type in your expression.\n");
scanf ("%f %c %f", &num1, &operator, &num2);

if(operator == 'S'){
printf(" = %.2f\n",num1);
res = num1;
while(1){
printf ("Type in your expression.\n");
scanf ("%c %f", &operator, &num2);
if(operator == '+'){
res += num2;
printf("%.2f\n", res);
}
else if(operator == '-'){
res -=num2;
printf("%.2f\n",res);
}
else if(operator == '*'){
res *=num2;
printf("%.2f\n",res);
}
else if(operator == '/'){
if(num2 == 0)
printf("Division by zero\n");
else
res /=num2;
printf("%.2f\n",res);

}
else if(operator == 'E'){
printf("End of the calculation:");
printf("%.2f",res);
break;

}
}
}


In this part of code the division and multiplication works fine:
But when i tipp smth like "+3" or "-2" during the accumulator nothing happens. I can't figure out where is the problem.

Answer

I think that's because in the below command :

scanf ("%c %f", &operator, &num2);

When you type +3 while the program is waiting to read an operator and a number it takes +3 as a number and not + as an operator and 3 as a number .So you have to give + 3 (with as apace separating). I tried it and i think it works!!