gpt4 book ai didi

c - ANSI C/rand() % 7 第一个值始终为 3

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

所以试图找出 C 中 rand() mod k7 的特殊之处。在另一篇文章中有人说 C rand() 使用 http://en.wikipedia.org/wiki/Linear_congruential_generator但我不明白是什么让 (mod k7) k-> 标量对于与 ANSI C 相关的算法有特殊意义。

所以我有以下代码:

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>

void getRand(int* num1, int* num2, int* num3);


int main(int argc, const char * argv[])
{
int i = 0;
for (i = 0; i < 100; i++) {

srand(time(NULL));
printf("%d\n", rand() % 7 );

sleep(1);
}
return 0;
}

这总是打印 3。但是如果我使用任何 n 使得 7 不能整除 n,我会得到更好的第一个值序列。显然仍然不是随机的,但比 3 或一些 c mod 7 = 3 更好。

我特意以这种方式编写程序,并在循环中使用种子,以表明无论种子如何,第一个值始终返回 3。

是的,我可以获得 Xn n > 0 的随机数但我想要X1 % 7 != X1 % 7对于每个 Xo。

最佳答案

好吧,让我们首先看看不仅仅是几个数据点:

#include <stdio.h>
#include <time.h>
#include <stdlib.h>


int main(int argc, const char * argv[])
{
size_t counters[7] = {0,0,0,0,0,0,0};
time_t tt = time(NULL);

//for (size_t i = 0; i < 7; i++) {
// printf("result: %d count: %d\n", i, counters[i]);
//}

for (size_t i = 0; i < 1000000; i++) {
srand(tt + i);
counters[rand() % 7] ++;
}

for (size_t i = 0; i < 7; i++) {
printf("result: %d count: %d\n", i, counters[i]);
}
}

有了这个,在 Windows 7 上,Visual Studio 2013 编译为 C++ 我得到

result: 0 count: 142894
result: 1 count: 142850
result: 2 count: 142848
result: 3 count: 142855
result: 4 count: 142854
result: 5 count: 142845
result: 6 count: 142854

你会得到什么,因为我怀疑你会从更大的数据集中得到更好的结果。

关于c - ANSI C/rand() % 7 第一个值始终为 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24458136/

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