我正在尝试制作一个包含最多 63 个位置的数组的程序。用户指定数组的实际事件位置,这些位置的起始值均为 0。
我想: 扫描数组的事件位置以及位于 0+4*n 和 3+4*n 的位置(其中 n=0,1,2,3,4, ((total-5)/4) 检查如果值为 0,如果是,则将其设为 1。 对于之前搜索中未包含的数组的最后 5 个事件位置,我将只检查数组的五个位置中的第一个和最后一个。如果值为 0,则将其设为 1。 在所有情况下,我一次只想更改一个值。如果找到零,则给出 1 的值,然后停止。 如果以上的值都不是 0 -> 有错误信息。
我的问题是在最后一部分的错误消息中当其他 if 语句激活时开始运行..
#include <stdio.h>
int main(void)
{
int array[63];
int i,n,total;
char selection;
for (i=0; i<63; i++)
array[i] = 0;
printf("Enter active array places (maximum 63):");
scanf(" %d",&total);
do{
printf("0.Exit \n");
printf("1.List array \n");
printf("2.Change value of array: \n");
scanf(" %c",&selection);
if (selection=='1')
{
for (i=0; i<total; i++)
printf("%d \n", array[i]);
}
else if (selection=='2')
{
for (i=0; i<(total); i++)
{
if ((i%4==0) && i<(total-5)&&(array[i]==0))
{
array[i]=1;
printf("You changed array value in place %d, ",i);
break;
}
else if ((i%4==3)&&i<(total-5)&&(array[i]==0))
{
array[i]=1;
printf("You changed array value in place %d, ",i);
break;
}
else if (i==(total-5)&&(array[i]==0))
{
array[i]=1;
fprintf("You changed array value in place %d, ",i);
i=n=total+1;
break;
}
else if (i==(total-1)&&(array[i]==0))
{
array[i]=1;
printf("You changed array value in place %d, ",i);
i=n=total+1;
break;
}
else
printf("Nothing to change");
}
}
}
} while (selection!='0');
}
最佳答案
您的代码比需要的要复杂一些(请参阅@Barmar 的评论)。
但是,如果我们按目前的方式使用您的代码,处理错误消息的一种方法是将打印从循环中取出并使用变量来记住是否发生了某些更改。
类似于:
int item_changed = 0; // In the start of the code before the for-loop
和
if ((i%4==0) && i<(total-5)&&(array[i]==0))
{
array[i]=1;
printf("You changed array value in place %d, ",i);
item_changed = 1; // Add this in all 4 places where you change the array
break;
}
去掉这部分
else
printf("Nothing to change");
并将其放在 for 循环之后。
if (item_changed == 0)
printf("Nothing to change");
关于c - 嵌套 for 循环改进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40594615/