【发布时间】:2016-12-13 08:54:57
【问题描述】:
您好,请考虑以下简单程序:
int main(void)
{
//exercise 1
float num2;
printf("please enter a number \n");
scanf_s("%f", &num2);
printf("the number multiple by 3 is %3.3f\n", num2 * 3);
//exercise 2
char ch1, ch2, ch3, ch4;
printf("enter a word with four char\n");
ch1 = getchar();
ch2 = getchar();
ch3 = getchar();
ch4 = getchar();
printf("the chars in reverse order are\n");
putchar(ch4);
putchar(ch3);
putchar(ch2);
putchar(ch1);
putchar('\n');
}
输出是:
please enter a number
2
the number multiple by 3 is 6.000
enter a word with four char
ffff
the chars in reverse order are
fff
3 个字符打印到控制台,如果我将练习 2 的代码块移到 1 上方:
int main(void)
{
//exercise 2
char ch1, ch2, ch3, ch4;
printf("enter a word with four char\n");
ch1 = getchar();
ch2 = getchar();
ch3 = getchar();
ch4 = getchar();
printf("the chars in reverse order are\n");
putchar(ch4);
putchar(ch3);
putchar(ch2);
putchar(ch1);
putchar('\n');
//exercise 1
float num2;
printf("please enter a number \n");
scanf_s("%f", &num2);
printf("the number multiple by 3 is %3.3f\n", num2 * 3);
}
结果如预期:
enter a word with four char
ffff
the chars in reverse order are
ffff
please enter a number
2
the number multiple by 3 is 6.000
我想知道为什么当我更改代码块的顺序时它会起作用以及如何解决它,谢谢。
【问题讨论】:
-
非常常见的常见问题解答。您在输入缓冲区中留下了换行符。例如,请参阅链接的副本,“当 *scanf() 无法按预期工作时”部分。