我写的代码如下:
#include<stdio.h>
int main() {
char o,r;
int x,y;
do {
printf("Enter operator: '+' or '-' or '*' or '/'n");
scanf("%c",&o);
printf("Enter first number: ");
scanf("%d",&x);
printf("Enter second number: ");
scanf("%d",&y);
switch(o) {
case '+':
printf("Sum: %d",x+y);
break;
case '-':
printf("Subtract: %d",x-y);
break;
case '*':
printf("Multiply: %d",x*y);
break;
case '/':
printf("Division: %d",x/y);
break;
default:
printf("Wrong operator entered.");
}
printf("nEnter y or Y to continue: ");
scanf("%c",&r); // r is not getting value?. why?
} while((r=='y')||(r=='Y'));
}
r没有得到值,因此它没有做它应该做的事情。
printf("nEnter y or Y to continue: ");
scanf("%c",&r);
有什么问题吗?我错过什么了吗?
如果我使用cin,
,为什么这段代码在c++中工作得很好,但当我在c中使用scanf
时却失败了?
您需要添加一行(或类似的内容):
while(getchar() != 'n');
输入第二个数字后,换行符'n'
留在stdin
中,放在r
中。
可以通过在while
循环之后添加以下行来证明这一点:
if(r == 'n')
printf("nnewlinen");
输入操作符:'+'或'-'或'*'或'/'
*
输入第一个数字:5
输入第二个数字:6
繁殖:30
输入y或y继续:
换行符
检查下面
#include<stdio.h>
int main()
{
char o,r;
int x,y;
do{
printf("Enter operator: '+' or '-' or '*' or '/'n");
scanf(" %c",&o);
printf("Enter first number: ");
scanf("%d",&x);
printf("Enter second number: ");
scanf("%d",&y);
switch(o)
{
case '+':
printf("Sum: %d",x+y);
break;
case '-':
printf("Subtract: %d",x-y);
break;
case '*':
printf("Multiply: %d",x*y);
break;
case '/':
printf("Division: %d",x/y);
break;
default:
printf("Wrong operator entered.");
}
printf("nEnter y or Y to continue: ");
scanf(" %c",&r);
} while((r=='y')||(r=='Y'));
}