习题6-7 简单计算器 (20分)
代码:
#include <stdio.h>
int main()
{
char regular[1024];
scanf("%s", ®ular);
int i = 0, sum = 0, num = 0;
char reg;
while (regular[i] >= '0' && regular[i] <= '9') {
sum = sum * 10 + (regular[i] - '0');
i++;
}
while (1){
if (regular[i] == '=') break;
if (regular[i] == '+' || regular[i] == '-' || regular[i] == '*' || regular[i] == '/') {
reg = regular[i];
i++;
}
else if (regular[i] >= '0' && regular[i] <= '9'){
num = 0;
while (regular[i] >= '0' && regular[i] <= '9') {
num = num *10 + (regular[i] - '0');
i++;
}
if (num == 0 && reg == '/') {
printf("ERROR");
return 0;
}
switch (reg) {
case '+': sum += num; break;
case '-': sum -= num; break;
case '*': sum *= num; break;
case '/': sum /= num; break;
}
}
else {
printf("ERROR");
return 0;
}
}
printf("%d", sum);
return 0;
}