I am tryings to create a simple calculator... I am learning C program. I need to write a program to create a calculator using switch statement. When I try to run this code the program stops in the middle of it when running and I didn't know what is causing this. Here is the program.
#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');
}
You have a problem with the buffer. Try this correction that I made
#include<stdio.h>
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.