一个最简单的计算器,支持+、-、*、/四种运算。仅需考虑输入输出为整数的情况,数据和运算结果不会超过int 表示的范围。
简单计算器
Description
一个最简单的计算器,支持+、-、*、/四种运算。仅需考虑输入输出为整数的情况,数据和运算结果不会超过int 表示的范围。
Input
输入只有一行,共有三个参数,其中第 1、2 个参数为整数,第 3 个参数为操作符(+、-、*、/)。
Output
输出只有一行,一个整数,为运算结果。然而: 1. 如果出现除数为 0 的情况,则输出:Divided by zero!; 2. 如果出现无效的操作符 (即不为+、-、*、/之一),则输出:Invalid operator!。
Sample Input 1
1 2 +
Sample Output 1
3
Sample Input 2
1 0 /
Sample Output 2
Divided by zero!
Sample Input 3
1 0 XOR
Sample Output 3
Invalid operator!
Hint
可以考虑使用if 和switch 结构。
Source
none
具体代码:#include<stdio.h>
int main ()
{
char c;
int a ,b ,d;
scanf("%d %d %c",&a,&b,&c);
switch ( c )
{
case ‘+’: printf("%d\n",d,d = a +b);break;
case ‘-’: printf("%d\n",d, d =a-b);break;
case '’: printf("%d\n",d, d = ab);break;
case ‘/’:
if (b ==0)
printf(“Divided by zero!\n”);
else
{
if (b != 0)
printf("%d\n",d,d = a /b);}
break;
default : printf (“Invalid operator!\n”);
}
return 0;
}