gpt4 book ai didi

C - 数组。仅更改特定值

转载 作者:太空宇宙 更新时间:2023-11-04 08:09:27 25 4
gpt4 key购买 nike

我正在尝试搜索一个数组,并且只检查特定的值(第 4 个、第 5 个等等)- ((0+n*4) 和 (3+n*4)。将检查找到的第一个,如果它的值为 0,则将其更改为 1,然后程序应停止。如果不是,它将尝试下一个值,依此类推。我有以下代码,但它不会停止..它一次使所有值都为 1..有什么建议吗?

        {
for (i=0; i<(totalnumber); i++)
{ for (n=0; n<((totalnumber)/4); n++)
{ if (i==(0+(n*4)))
{ if (array[i]==0)
{
array[i]=1;
break;
}
}

else if ((i==(3+(n*4))))
{
if (array[i]==0)
{
array[i]=1;
break;
}
}
}
}
}

最佳答案

使用单个 break 语句只会跳出最近的循环。它不会跳出外部 i 循环。因此,也更改您的代码以跳出外循环。

另一种方法是在同一个 for 循环中同时使用计数器变量 i,n。这意味着,您只需使用一次 break 即可跳出外部 for 循环。

我引用自MSDN

Within nested statements, the break statement terminates only the do, for, switch, or while statement that immediately encloses it. You can use a return or goto statement to transfer control elsewhere out of the nested structure.

这是相关的 - Can I use break to exit multiple nested for loops?

关于C - 数组。仅更改特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40575627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com