- 论坛徽章:
- 0
|
近日做练习时遇到这么个习题,要求打印到n为止的自然数和其平方值,并在每24个之后暂停,显示"Press Enter to continue...", 按下enter后继续。小弟想了几次都写错了,这个时作者给出的答案:
int main(void)
{
int i, n;
char ch;
printf("This program prints a table of squares.\n");
printf("Enter number of entries in table: ");
scanf("%d", &n);
ch = getchar();
/* dispose of new-line character following number of entries */
/* could simply be getchar(); */
for (i = 1; i <= n; i++) {
printf("%10d%10d\n", i, i * i);
if (i % 24 == 0) {
printf("Press Enter to continue...");
ch = getchar(); /* or simply getchar(); */
}
}
return 0;
}
对这一段很是困惑
scanf("%d", &n);
ch = getchar();
/* dispose of new-line character following number of entries */
/* could simply be getchar(); */
为何在刚输入n后就用getchar?这个getchar不是读入了输入n之后的回车,但没有保存么?这行getchar和后面的暂停有什么关系呢?
试过去掉这一行,程序无法停下。
请大家帮忙解惑。 |
|