- #1

Eclair_de_XII

- 1,068

- 90

- TL;DR Summary
- I am tasked to write a calculator. It will accept user input in the form: (operator) (operand). The range of operations include: set (s), end (e), and the usual arithmetic operations.

C:

```
#include <stdio.h>
void calculate(float *accumulator,char operator,float number){
switch(operator){
case 's':
*accumulator=number; break;
case '+':
*accumulator+=number; break;
case '-':
*accumulator-=number; break;
case '*':
*accumulator*=number; break;
case '/':
if (number != 0)
*accumulator/=number;
else
printf("Stop dividing by zero!\n");
break;
}
}
int main(void){
float number,*accumulator;
char operator='\0';
printf("Begin Calculations\n");
while (operator != 'e') {
scanf("%c %f",&operator,&number);
calculate(accumulator,operator,number);
printf("= %.6f\n\n",*accumulator);
}
return 0;
}
```

When I run this code, it seems to read the print statement twice on subsequent calculations. Moreover, when I need to add or subtract things, I will need to type in the appropriate operator symbols twice. I do not know why that is.

EDIT: For some reason, it seems to function properly if I transpose the order of the scanf arguments; but it does go on in an infinite loop if I give erroneous input. But this does not answer my question.

Last edited: