c - 生成一个介于 1 和 N-1 之间的随机数

标签 c random

<分区>

Possible Duplicate:
How to generate a random number from within a range - C

您将如何生成介于 1 和 N-1 之间的随机数,其中 N 是用户输入的数字?

到目前为止,我的代码是:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int number = 0; //number variable
    printf("This program will ask you for a number, an integer, and will print out a    random number from the range of your number 1, to N-1.");//output that explains the program's purpose and use to the user.
    //gets the input
    fgets(buffer, sizeof(buffer), stdin);
    sscanf(buffer, "%d", &number); //gets the input and stores it into variable number

    return (0);

最佳答案

尝试这样的事情:-

unsigned int
randomr(unsigned int min, unsigned int max)
{
       double x= (double)rand()/RAND_MAX;

       return (max - min +1)*x+ min;
}

查看此链接:- http://c-faq.com/lib/randrange.html

关于c - 生成一个介于 1 和 N-1 之间的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14403951/

相关文章:

algorithm - 重复有偏见的随机洗牌会减少偏见吗?

c - C 中具有数组原型(prototype)的结构

c - 从函数返回结构体?

c - 从C语言的文本文件中读取信息

r - 种子设置 : why is the output different after no change in input

Android内容提供者随机排序

c++ - OpenCV - 人脸检测 : Rectangle around face

c++ - 将函数声明为 pure 或 const 对 GCC 的影响(如果不是)

java - 随机生成方程和答案

SQL:如何从一个表中为另一个表中的每一行获取随机数的行