gpt4 book ai didi

c - 嵌套 for 循环 : why is the condition stated in for() ineffective?

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

因此对于下面的代码,我希望 C 程序显示 1 到 999 之间的奇数(不是 3 的倍数),一行中显示 9。

1   5   7   11   13   17   19   23   25

29 31 .. and so on.

下面是我使用的代码。虽然我确实弄清楚了如何让它工作 - if (i >=999) break;线路有帮助,我不明白为什么i如果该断线不存在,则超过 999。换句话说,条件 i < 999在两个循环中都是无效的。

有人能帮我理解为什么会这样吗?

我在类里面使用 Microsoft Visual Studio 2005。

#include <stdio.h>

void main(void)
{
int i, j;

for(i = 1; i < 999; i++)
{
for(j = 0; i < 999, j< 9; i++, j++)
{
if (i%2 == 0 || i%3 == 0) {
j = j-1;
if (i >=999) break;
continue;
}
printf("%-3d ", i);
if (j == 8) break;
}
printf("\n");
}
}

最佳答案

因为你的原始代码有点复杂,我认为从头开始回答你的问题是最容易的。这是一个实现你想要的 C 代码,它比 OP 简单得多:

void main(void) {
int counter = 0;

for (int i=0; i < 1000; ++i) {
if (i % 2 != 0 && i % 3 != 0) { // if not even (i.e. odd) AND not divisible by 3
if (counter == 9) { // start a new line for each 9 numbers
printf("\n");
counter = 0; // reset the counter
}
printf("%-3d ", i);
++counter; // increment counter for each new number
}
}
}

我认为您不需要也不应该在解决方案中使用双 for 循环。 for 循环中的条件也显得非常复杂。此解决方案一次遍历 0 到 999 之间的所有数字,并生成所需的输出。

关于c - 嵌套 for 循环 : why is the condition stated in for() ineffective?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31667819/

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