gpt4 book ai didi

c - For 循环未按预期工作

转载 作者:太空宇宙 更新时间:2023-11-04 01:47:01 28 4
gpt4 key购买 nike

当我运行这段代码时,printf() 函数似乎给出了一个随机的大数,就好像它正在调用一个越界的数组。这是怎么回事?

#include <stdio.h>
#include <math.h>

int main(void)
{
int test_num = 1000;
int factors[16];

for(int i = 1, j = 0; i < test_num; i++, j++) {
if(test_num % i == 0)
factors[j] = i;
}

printf("%d", factors[2]);

return 0;
}

最佳答案

问题很可能是您正在递增 j即使您不分配 i .

你得到的因子序列是 1、2、4、5、8、10,...你可能想将它们分配给索引 0-5(含),而不是 0、1、3、4, 7、9 等

按如下方式更改循环:

for(int i = 1, j = 0; i < test_num && j < 16; i++) {
if(test_num % i == 0) {
factors[j] = i;
j++;
}
}

重点只是自增j什么时候i符合你的标准。您还想确保您没有越界 ( && j < 16 )。

关于c - For 循环未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51883502/

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