C 当outer if为非真时,为什么它进入else块?
这是我的代码:当我为数组输入的输入是10001时。然后它也在else块中输入[1]=0,其中我在outer中设置了条件if,if(input[j]=1)。有人能告诉我为什么会发生这种情况吗C 当outer if为非真时,为什么它进入else块?,c,C,这是我的代码:当我为数组输入的输入是10001时。然后它也在else块中输入[1]=0,其中我在outer中设置了条件if,if(input[j]=1)。有人能告诉我为什么会发生这种情况吗 #include<stdio.h> int main() { unsigned int tcase=0,build=0,i=0,j=0,k=0,count=0; unsigned int input[1000]; scanf("%d",&tc
#include<stdio.h>
int main()
{
unsigned int tcase=0,build=0,i=0,j=0,k=0,count=0;
unsigned int input[1000];
scanf("%d",&tcase);
while(tcase--)
{
scanf("%d",&build);
for(i=0;i<build;i++)
scanf("%d",&input[i]);
for(j=0;j<build;j++)
{
if(input[j]==1)
{
if(j==0)
{ input[j+1]=1;
printf("fddf");
}
else if(j==(build-1))
{
input[j-1]=1;
printf("Gfgf");
}
else
{
input[j+1]=1;
input[j-1]=1;
printf("awGfgf");
}
}
}
for(k=0;k<build;k++)
{
if(input[k]==0)
++count;
}
printf("%d\n",count);
}
return 0;
}
#包括
int main()
{
无符号int-tcase=0,build=0,i=0,j=0,k=0,count=0;
无符号整数输入[1000];
scanf(“%d”和&tcase);
while(tcase--)
{
scanf(“%d”,构建(&d));
对于(i=0;i,这是因为您正在检查超过数组边界末端的值,使用不确定的值测试内存
您的数组定义为
unsigned int input[1000];
声明
if(input[j]==1)
当j为10001时,测试内存超过数组边界的末端。内存的值未定义,实际上取决于许多因素。该内存地址的值不太可能为1(事实上,如果内存确实随机初始化,则概率为1/2^32).我将根据您对Eric J答案的评论回答您的问题:
J.no u got it wrong by i/p 10001 i mean for input[0]=1,input[1]=0 and so on... so it only occupies 5 array spaces
答案的要点是,您输入的第一个输入为1,这将导致条件第一次成功。在每次迭代中,您将不断更改输入数组的值,从而导致后续迭代进入条件
正如你提到的,你的意见是
input[0] = 1
input[1] = 0
input[2] = 0
input[3] = 0
input[4] = 1
现在,请参见以下代码中的行为:
for(j=0;j< build;j++)
{
if(input[j]==1) /* First for input[0], this condition succeeds */
{
if(j==0)
{
input[j+1]=1; /* This line changes input[1] to 1, so next time in the loop the condition if(input[j] == 1 will succeed */
printf("fddf");
}
else if(j==(build-1)) /* This condition will cause input[4] to be set to 1 and will cause if(input[j] == 1) to succeed for the last iteration of the loop */
{
input[j-1]=1;
printf("Gfgf");
}
else /** This condition will cause input[2] & input[3] to be set to 1 and will again cause if(input[j] == 1) to succeed in successive loop iterations **/
{
input[j+1]=1;
input[j-1]=1;
printf("awGfgf");
}
}
}
(j=0;j
{
如果(输入[j]==1)/*首先输入[0],则此条件成功*/
{
如果(j==0)
{
input[j+1]=1;/*此行将input[1]更改为1,因此下次在循环中,条件if(input[j]==1)将成功*/
printf(“fddf”);
}
else if(j==(build-1))/*此条件将导致输入[4]设置为1,并导致if(输入[j]==1)在循环的最后一次迭代中成功*/
{
输入[j-1]=1;
printf(“Gfgf”);
}
else/**此条件将导致输入[2]和输入[3]设置为1,并再次导致if(输入[j]==1)在连续循环迭代中成功**/
{
输入[j+1]=1;
输入[j-1]=1;
printf(“awGfgf”);
}
}
}
J.no u i/p 10001搞错了,我的意思是输入[0]=1,输入[1]=0等等……因此它只占用5个数组空间。这是预期的结果。它输入是因为在上一次迭代(迭代J=0)中,您将输入[1]的值更改为1。