c语言关于getchar()简单问题

来源:百度知道 编辑:UC知道 时间:2024/05/30 14:41:00
以下是一个简单的数列求和程序,我的问题是最后为何用两个getchar()函数,一般都是用一个就可以。经过上机实践的确要用两个getchar()才可以在最后暂时停止程序运行。请解释,谢谢。
#include <stdio.h>
main()
{
int i,j,n;
long sum=0,temp=0;

printf("Please input a number to n:\n");
scanf("%d",&n);
if(n<1)
{
printf("The n must no less than 1!\n");
return;
}

for(i=1;i<=n;i++)
{
temp=0;
for(j=1;j<=i;j++)
temp+=j;
sum+=temp;
}
printf("The sum of the sequence(%d) is %d\n",n,sum);
getchar();
getchar();
}
下面的也有scanf("%d",&matrixA[i][j]);语句,为何用一个getch();就可以?想知道什么时候用两个getch();什么时候用一个就可以了?
/* 用二维数组实现矩阵的转置 */
#include <stdio.h>
#define ROW 3
#define COL 4
main()
{
int matrixA[ROW][COL],matrixB[COL][ROW];
int i,j;

clrscr();
printf("Enter elements of the matrixA,&q

scanf("%d",&n);

因为在以上语句读取数据时,你实际上在结尾输入了一个回车,而这个回车符不能通过上语句读取所以还留在缓冲区中等待下一次读取,而结尾处的第一个getchar();就是用于读取这个回车符的,第二个getchar()才是等待再次按回车的。

第一个用来接收上面的输入时候按下的回车