It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center
                            
                        
                    
                
                                6年前关闭。
            
                    
我正在尝试解决项目欧拉的问题5,而我一直得到的答案是错误的:

#include <stdio.h>

main()
{
    int num;
    int x = 0;
    for (num = 20; x == 0; num++)
    {
        if ((num%1) == 0 && (num%2) == 0 && (num%3) == 0 && (num%4) == 0 && (num%5) == 0 && (num%6) == 0 && (num%7) == 0 && (num%8) == 0 && (num%9) == 0 && (num%10) == 0 && (num%11) == 0 && (num%12) == 0 && (num%13) == 0 && (num%14) == 0 && (num%15) == 0 && (num%16) == 0 && (num%17) == 0 && (num%18) == 0 && (num%19) == 0 && (num%20) == 0)
        x = 1;
    }
    printf("%d %d", num, x);
}


我的程序不断打印232792561(我知道我正在打印x,这仅仅是出于故障排除的目的)。

我得到的逐字输出是:232792561 1

我做了一些研究,发现问题的正确答案是232792560
我现在开始认为问题出在for循环中。

循环首先做什么,迭代(num++)还是测试(x == 0)?

最佳答案

在执行循环主体之后(如果有的话,因为首先运行初始化代码,然后检查条件以查看是否输入了主体),


首先运行更新代码
然后检查条件。


因此,将x设置为1后,num会再次增加。

不用将x设置为1即可结束循环,您可以简单地break;,这样就可以退出循环而无需运行更新代码。

10-07 19:08
查看更多