我是C的初学者.如果我的问题很蹩脚,请不要介意.在我编写的这个程序中,当我第一次使用'for'循环时,我预计只有3个值存储在一个数组中,但它存储了4个值,并且在下一个'for'循环中,如预期的那样显示3个值.我的问题是为什么在第一个'for'循环中它需要4个值而不是3个?
#include<stdio.h>
void main()
{
int marks[3];
int i;
for(i=0;i<3;i++)
{
printf("Enter a no\n");
scanf("%d\n",(marks+i));
}
for(i=0;i<3;i++)
{
printf("%d\n",*(marks+i));
}
}
Run Code Online (Sandbox Code Playgroud)
San*_*oel 11
\n在这scanf是问题
#include<stdio.h>
int main()
{
int marks[3];
int i;
for(i=0;i<3;i++)
{
printf("Enter a no\n");
scanf("%d",(marks+i));
}
printf("\nEntered values:\n");
for(i=0;i<3;i++)
{
printf("%d\n",*(marks+i));
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
原因:
我希望只有
3值存储在一个数组中,但它存储4个值,并在下一个'for'循环中按预期显示3个值.我的问题是为什么在第一个'for'循环中它需要4个值而不是3个?
第一: 不,它只存储3数字而不是4数字marks[].
第二:有趣的理解循环只运行三次i = 0到i < 3.for循环根据条件运行.更有趣的代码scanf()如下所述:
你的困惑是为什么你必须输入四个数字,这不是因为你循环运行4时间而是因为scanf()函数仅在你输入非空格字符时返回(并且在一些enter按下之后输入一个非空格字符的数字符号).
要了解此行为,请阅读手册int scanf(const char *format, ...);:
一系列空格字符(空格,制表符,换行符等;请参阅参考资料
isspace(3)).该指令 在输入中匹配任意数量的空白,包括无空格.
因为在第一个for循环中,在 scanf()你已经包含\n在格式字符串中,所以scanf()只有在按下数字enter(或非空格key)时才返回.
scanf("%d\n",(marks+i));
^
|
new line char
Run Code Online (Sandbox Code Playgroud)
怎么了?
假设对程序的输入是:
23 <--- because of %d 23 stored in marks[0] as i = 0
<enter> <--- scanf consumes \n, still in first loop
543 <--- scanf returns, and leave 542 unread,
then in next iteration 543 read by scanf in next iteration
<enter>
193
<enter> <--- scanf consumes \n, still in 3rd loop
<enter> <--- scanf consumes \n, still in 3rd loop
123 <--- remain unread in input stream
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38214 次 |
| 最近记录: |