本帖最后由 why19910522 于 2015-7-2 15:40 编辑
由用户输入表达式,然后输出结果
void caculator(){ //定义变量,两个数x和y,算术运算符op int x = 0,y = 0; char op; float result = 0.0f; //提示用户输入表达式 printf("请输入表达式:(请不要输入空格!)\n"); scanf("%d%c%d",&x,&op,&y); //校验:
//除数不能为0 for (;op == '/' && y == 0;){ printf("除数不能为0,请重新输入表达式:\n"); scanf("%d%c%d",&x,&op,&y); }
switch (op) { case '+': result = x + y; printf("结果是%d\n",result); break;
case '-': result = x - y; printf("结果是%d\n",result); break;
case '*': result = x * y; printf("结果是%d\n",result); break;
case '/': result = x / (float)y; printf("结果是%.2f\n",result); break;
}
}
|