欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

习题6-7 简单计算器 (20分)

程序员文章站 2022-06-07 16:53:18
...

习题6-7 简单计算器 (20分)

习题6-7 简单计算器 (20分)
代码:

#include <stdio.h>
int main()
{
 char regular[1024];
 scanf("%s", &regular);
 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;
}
相关标签: c语言编程题