|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
目的是输出平方表,并且每实现24次平方就等待回车继续 为什么这段代码不对
#include <stdio.h>
int main()
{
int n,x=0;
printf("This program prints a table of squares.\n");
printf("Enter number of entries in table:");
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
printf("%10d%10d\n",i,i*i);
if(x<24)
x++;
else{
printf("Press Enter to continue..");
if (getchar()=='\r') {
x=0;
}
}
}
return 0;
}
首先由前面几位大佬所说,这种情况最好用%;
不过如果执意用你的方法,需要以下几处修改:
1、int i=1;写在前面而不是for内
2、getchar()读取的回车键不是'\r'而是'\n',所以应将'\r'改为'\n'
3、你仔细观察你写的for循环中的x你会意识到,你每次输出的数据数是25个(x==0~x==24)而不是24个,所以应将<24改为<23
4、处理完以上三点你会发现,第一次输出的是48个数据(以后每次24个),这是因为你在scanf后打的回车中的'\n'还保存在缓存区中(输入流问题),故应在scanf后加个getchar();将'\n'消耗掉
修改后的代码如下:
#include <stdio.h>
int main()
{
int n,x=0;
int i=1;
printf("This program prints a table of squares.\n");
printf("Enter number of entries in table:");
scanf("%d",&n);
getchar();
for(;i<=n;i++)
{
printf("%10d%10d\n",i,i*i);
if(x<23)
x++;
else
{
printf("Press Enter to continue..");
if (getchar()=='\n')
{
x=0;
}
}
}
return 0;
}
不过我还是建议你用闪电猫网络的方法
|
|