随机数数组的C程序实现

e0bqpujr  于 2023-03-01  发布在  其他
关注(0)|答案(4)|浏览(111)

我是C程序新手,我需要创建100个50到70之间的随机数,并将它们存储在一个双精度数组中。我该如何开始呢?

ndh0cuux

ndh0cuux1#

创建阵列:

int my_array[100];

为随机数生成器设定种子

srand(0);

循环遍历数组并填充它!:

int i;
for (i = 0; i < 100; i++) {
    my_array[i] = rand();
}

这是一个开始,但是兰德()的取值范围比你想要的随机数取值范围要大得多,有很多方法可以缩小取值范围,如果你不在乎随机数是否完全随机,你可以使用modulo运算符,其中13 % 10 = 3
这是为int s准备的,我想给读者留下一些乐趣。

gojuced7

gojuced72#

如果数字在50和70之间,那么我会说,尝试modulo和c的兰德()函数。所以首先,因为你想使用随机数,我建议包括标准库。

#include <stdlib.h>`

double bal[100];

for (int f = 0; f < 100 ;f++) {
    bal[f] = (rand() % 20) + 50;
}

I模20的原因是因为50和70的差是20,所以,如果你假设50是零,那么70将是20,所以我们将产生的任何数字都将在这些数字之间。希望它能有所帮助!*/

uidvcgyl

uidvcgyl3#

你可以用这个来定义rand函数的范围:

rand() % (max_number + 1 - minimum_number) + minimum_number
brc7rcf0

brc7rcf04#

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

void gen_random_numbers(int *array, int len, int min, int max){
    for (int i = 0; i < len; i++)
        array[i] = rand() % (max - min + 1) + min;
}

int main() {
    system("cls");
    srand(time(0));

    int numbers[100] = {};
    gen_random_numbers(numbers, 100, 50, 70);
    // create 100 arrays, each of them is in range of [50, 70]
    
    return 0;
}

相关问题