C语言 使用C程序的随机数数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22186423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Array of random numbers using C program
提问by user3381419
Im new to C program and I am required create 100 random numbers between 50 and 70, and store them in an array of double. How do I start?
我是 C 程序的新手,我需要在 50 到 70 之间创建 100 个随机数,并将它们存储在一个双精度数组中。我该如何开始?
回答by Scott Lawrence
Create an array:
创建一个数组:
int my_array[100];
Seed the random number generator
播种随机数生成器
srand(0);
Loop over your array and fill it up!:
循环遍历您的数组并将其填满!:
int i;
for (i = 0; i < 100; i++) {
my_array[i] = rand();
}
That's a start. However, the range of rand() is much larger than the range of random numbers you want. There are many ways to narrow the range. If you don't care about the numbers being perfectlyrandom, you can use the modulo operator, where 13 % 10 = 3.
那是一个开始。但是,rand() 的范围远大于您想要的随机数范围。有很多方法可以缩小范围。如果您不关心数字是完全随机的,则可以使用模运算符,其中13 % 10 = 3.
This is for ints. I want to leave some fun for the reader.
这是为ints。我想给读者留下一些乐趣。
回答by Mohamed Mnete
If the number is between 50 and 70, then I would say, try modulo and the rand() function of c. So firstly since you will want yo use random numbers, I would advice including the standard library. Do:
如果数字在 50 到 70 之间,那么我会说,尝试取模和 c 的 rand() 函数。所以首先,因为你会希望你使用随机数,我建议包括标准库。做:
#include <stdlib.h>`
double bal[100];
for (int f = 0; f < 100 ;f++) {
bal[f] = (rand() % 20) + 50;
}
The reason why I modulo 20 is because the difference between 50 and 70 is 20 so, if you assume 50 is zero then 70 will be 20 and so any number we will produce will be between these numbers. Hope it helps! */
我对 20 取模的原因是因为 50 和 70 之间的差是 20,所以,如果您假设 50 为零,那么 70 将是 20,因此我们将产生的任何数字都将介于这些数字之间。希望能帮助到你!*/

