用户通过键盘输入数据和运算符,则程序可根据用户输入的内容给出计算结果。只要求完成 +、-、*、/ 运算。
输入运算符时,只能输入+、-、*、/,运算符不可用数字代替,如果用户未按要求输入,如运算符不为+、-、*、/,则给出出错信息。
提示:首先提示用户输入两个浮点数和一个字符,通过switch分支结构判断字符是什么符号,进而进行相应的计算。
#include<stdio.h>
#include<stdlib.h>
int main(){
float a,b;
char c;
printf("enter 2 float numbers: ");
scanf("%f %f", &a, &b);
getchar();//清空缓存
do{
printf("\nenter a '+'、'-'、'*'or'/' \n");
printf("otherwise, it will require repeated input.\n: ");
scanf("%c", &c);
if(c=='+'||c=='-'||c=='*')
break;
else if(c=='/'){
if(b==0)
printf("invalid operation!\ntry other operations\n\n");
break;
}
}while(1);
switch(c){
case '+':
printf("%f + %f = %f", a, b, a+b);
break;
case '-':
printf("%f - %f = %f", a, b , a-b);
break;
case '*':
printf("%f * %f = %f", a, b, a*b);
break;
case '/':
printf("%f / %f = %f", a, b, a/b);
}
return 0;
}
刚学C语言不久,希望能得到道友们的指点,逐步优化代码,一天天进步❤