为什么这个循环在每个循环中打印相同的值?

时间:2015-11-09 13:39:07

标签: c function loops duplicates call

我在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

2 个答案:

答案 0 :(得分:1)

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

在循环外提取srand()

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

答案 1 :(得分:0)

因为你在循环中调用srand()。您总是在每次迭代中重置随机种子,因为time()具有秒精度,并且两次迭代之间的时间几乎不接近1 s

你应该在程序开始时只调用srand()一次,最好是main()函数。