void mul()
{
int x,y,sum = 0;
scanf("%d",&x);
scanf("%d",&y);
while (x != 0){
if (x%2 != 0)
sum = sum + y;
x = x/2;
y = 2*y;
}
printf("%d",sum);
}
int main()
{
char c;
printf("Enter two numbers and y to exit");
//mul();
scanf("%c",&c);
while (c != 'y'){
mul();
}
return 0;
}
在运行这个程序时,它不会在输入“y”时退出。为什么?
最佳答案
您不是在 while
循环中扫描。这样做:
char c = 'n';
while (c != 'y')
{
printf("Enter two numbers and y to exit");
scanf("%c",&c);
mul();
}
只是指出一些额外的东西,当你输入一个像 y
或 n
这样的字符并按下 ENTER 键时,一个字符(你输入的)和一个字符(这是输入键击 - 换行符)被放置在输入缓冲区中。第一个字符被 scanf
消耗,但换行符保留在输入缓冲区中。
解决方案是使用额外的换行符:
scanf(" %c", &c);
^<------------Note the space
关于c - 这里有什么逻辑错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19264557/