getchar()不等待输入并直接跳转到下一行。我认为scanf和getchar之间有一些不匹配,但无法确定到底是什么。
#include<stdio.h>
#include<ctype.h>
int main()
{
char ch;
int n1,n2;
printf("Enter the operation of your choice\n");
printf("a. add\ts. subtact\nm. multiply\td. divide\nq. quit\n");
while((ch=getchar())!='q')
{
printf("\nEnter 1st number:\n");
if(scanf("%d",&n1)!=1)
{
printf("Please enter an integer value.\n");
continue;
}
printf("Enter 2nd number:\n");
if(scanf("%d",&n2)!=1)
{
printf("Please enter an integer value.\n");
continue;
}
switch(ch)
{
case 'a':
{ printf(" %d + %d = %d\n",n1,n2,n1+n2);
break;
}
case 's':
{
printf(" %d - %d = %d\n",n1,n2,n1-n2);
break;
}
case 'm':
{
printf(" %d * %d = %d\n",n1,n2,n1*n2);
break;
}
case 'd':
{
if(n2!=0)
{
printf(" %d / %d = %f\n",n1,n2,(float)n1/n2);
break;
}
else
{
printf("Enter a non-zero number for n2\n");
continue;
}
break;
}
}
printf("Enter the operation of your choice\n");
printf("a. add\ts. subtact\nm. multiply\td. divide\nq. quit\n");
}
printf("Bye.");
}
输出:
输入您选择的操作
一个。加s。机智的
米d。划分
q。放弃
一个
输入第一个数字:
50
输入第二个数字:
25
50 + 25 = 75
输入您选择的操作
一个。加s。机智的
米d。划分
q。放弃
输入第一个数字:
当您给出scanf读取的值时,您的getchar会读取换行符和其他输入的空格
只需更换
通过
注意'%'之前的空格,这要感谢它绕过包括换行符在内的空格