我正在尝试创建一个简单的计算器... 我正在学习C程序。我需要编写一个程序来使用switch语句创建一个计算器。当我尝试运行此代码时,程序在运行时会在其中途停止,我不知道是什么原因导致的。 这是程序。
#include<stdio.h>
void main()
{
float n1,n2,ans;
char op,x;
do
{
printf("Enter 1:");
scanf("%f",&n1);
printf("Enter 2:");
scanf("%f",&n2);
printf("Enter operator:");
scanf("%c",&op);
switch(op)
{
case'+': ans=n1+n2;break;
case'-': ans=n1-n2;break;
case'*': ans=n1*n2;break;
case'/': ans=n1/n2;break;
default:printf("Invalid operator\n");
}
printf("Answer= %.2f\n",ans);
printf("Do you want to try it again?(y/n)");
scanf("%c",&x);
}
while(x=='y' || x=='Y');
}
答案 0 :(得分:0)
缓冲区有问题。尝试我所做的此更正
int main(){
float n1,n2,ans;
char op,x;
do{
printf("Enter 1:");
scanf("%f",&n1);
printf("Enter 2:");
scanf("%f",&n2);
getchar();
printf("Enter operator:");
scanf("%c",&op);
switch(op){
case'+': ans=n1+n2;break;
case'-': ans=n1-n2;break;
case'*': ans=n1*n2;break;
case'/': ans=n1/n2;break;
default:printf("Invalid operator\n");
}
printf("Answer= %.2f\n",ans);
printf("Do you want to try it again?(y/n)");
getchar();
scanf("%c",&x);
printf("%c\n",x );
}while(x=='y' || x=='Y');
return 0;
}