如何使用rand函数在一个特定的范围内,使数字? [英] How to use rand function to make numbers in a specific range?

查看:379
本文介绍了如何使用rand函数在一个特定的范围内,使数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

进行随机数在特定范围内如PIC 18-35之间的数字兰特????

to make random numbers in a specific range like pic a rand number between 18-35????

推荐答案

如果这是用C写的,那么你是pretty接近。编译这个code:

If this is written in C, then you are pretty close. Compiling this code:

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

int main() {
    int i;
    for (i = 0; i < 1000000; i++) {
        printf("%d\n", rand()%(35-18+1)+18);
    }
}

和管道中运行它产生这样的输出:

And running it in a pipeline produces this output:

chris@zack:~$ gcc -o test test.c
chris@zack:~$ ./test | sort | uniq -c
  55470 18
  55334 19
  55663 20
  55463 21
  55818 22
  55564 23
  55322 24
  55886 25
  55947 26
  55554 27
  55342 28
  55526 29
  55719 30
  55435 31
  55669 32
  55818 33
  55205 34
  55265 35

关键是你忘了添加1 - 的栅栏柱误差

您可以概括成一个函数这样的:

You can generalize this into a function:

int random_between(int min, int max) {
    return rand() % (max - min + 1) + min;
}

这篇关于如何使用rand函数在一个特定的范围内,使数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆