1 #include
2
3 int add(int a, int b);
4 int sub(int a, int b);
5 int mul(int a, int b);
6 int div(int a, int b);
7
8
9 int main(int argc, const char *argv[])
10 {
11 /*
12 * 定义接收变量,运算字符;
13 */
14 int a,b,d;
15 char ch;
16
17 /*
18 * 赋初值
19 */
20 a = 0;
21 b = 0;
22 ch = '0';
23
24
25 /*
26 * 控制台输入运算变量,运算符;
27 */
28 printf("请输入需要计算的数及运算符;格式如:'num1 +-x/ num2' \n");
29 scanf("%d%c%d",&a,&ch,&b);
30
31 /*
32 * 输入数据判断
33 */
34 while((ch != '+')&&(ch != '-')&&(ch != '*')&&(ch != '/'))
35 {
36 //fflush(stdin);此种清空缓冲区无效
37 setbuf(stdin,null);
38 printf("输入运算符有误,请重新输入:\n");
39 scanf("%c",&ch);
40 }
41
42 /*
43 * 除数为0做判断
44 */
45 if((ch == '/')&&(b==0))
46 {
47 setbuf(stdin,null);
48 printf("除数不能为0,请重新输入:\n");
49 scanf("%d",&b);
50 }
51
52
53 /*
54 * 识别不同运算字符,做不同的运算;
55 */
56 switch(ch)
57 {
58 case '+':
59 printf("%d+%d=%d\n",a,b,add(a,b));
60 break;
61 case '-':
62 printf("%d-%d=%d\n",a,b,sub(a,b));
63 break;
64 case '*':
65 printf("%d*%d=%d\n",a,b,mul(a,b));
66 break;
67 case '/':
68 printf("%d/%d=%d\n",a,b,div(a,b));
69 break;
70 default:
71 printf("error\n");
72 }
73
74 return 0;
75 }
76
77 /*
78 * 定义运算函数
79 */
80 int add(int a, int b)
81 {
82 return a+b;
83 }
84
85 int sub(int a, int b)
86 {
87 return a-b;
88 }
89
90 int mul(int a, int b)
91 {
92 return a*b;
93 }
94
95 int div(int a, int b)
96 {
97 return a/b;
98 }