gpt4 book ai didi

c - 为什么这个循环每次循环打印相同的值?

转载 作者:行者123 更新时间:2023-11-30 20:24:24 25 4
gpt4 key购买 nike

我在 main() 中有以下循环

while (count < 5){
//with 2^15 as the lower limit
srand(time(NULL));
ran_num = rand() % (65536 - 32769); //check READ ME Citation A
ran_num += 32769;
binary = Integer_to_Binary(ran_num);
count += Primality_Test(ran_num, binary, sizeof(binary));
}

printf声明位于 Primality_Test功能...

int Primality_Test(unsigned __int128 ran_num, int binary[], int num_bits){
int result = Modular_Exponentiation(ran_num, binary, num_bits);
if (result == 1){
//the number is prime
printf("[%d] passes the primality test as prime\n", ran_num); //print binary array too
return 1;
}
else{
//call Charmichael_Test
result = Charmichael_Test(ran_num);
//check for errors
if (result == 1){
//number is prime
printf("[%d] is a charmichael number\n", ran_num);
return 1;
}
else {
//number is not prime
//printf("This number is not prime");
return 0;
}
}

}

即使在调试时,ran_num 正在更改,我的输出始终是相同的数字

[57221] is a charmichael number
[57221] is a charmichael number
[57221] is a charmichael number
[57221] is a charmichael number
[57221] is a charmichael number

最佳答案

因为你在循环中调用了srand()。您使用 time(NULL) 给出以秒为单位的时间,因此 5 个循环中每个循环的值可能相同。由于 srand() 设置 rand() 序列的“起始”点,因此您具有相同的值。

srand() 提取到循环之外。

请注意,如果循环的值非常大,您将看到每秒打印值的变化。

关于c - 为什么这个循环每次循环打印相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33610402/

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