如何在C中生成一次范围内的随机数?

时间:2015-03-03 07:08:31

标签: c arrays random range srand

C语言编程新手,我试图生成一次随机数。但是当程序符合时,它会在用户指定的范围内生成30个随机数。使用数组会更容易吗?任何帮助都会很好。

修改

程序应提示用户输入要模拟的销售数量,范围从1到10000.接下来,每个模拟销售应该执行以下操作:选择随机员工来记录销售,随机确定销售的总金额,将该金额加到所选员工的运营销售总额中,并增加员工的销售数量。 - 这基本上就是我要做的。对不起困惑

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

int main (void)
{
    int n,c; // n is the number of sales to simulate, c is the counter
    int id[30];// id[30] is the number of employees 
    srand(time(NULL));
    int myVar;

    printf("Enter the number of sales to simulate: ");
    scanf("%d", &n);
    while(n<1 || n>10000)//blocking while loop
    {
        //prompt user to enter proper number for calculation
        printf("Error: Enter a proper number in the range from 1 to 10000: \a");
        scanf("%d",&n);
    }
    printf("Id\n");//prints out the id
    for (c = 0; c<30; c++)
    {
        id[c] = c;
        printf("%d: ",id[c]); //prints out the id numbers starting from 0 and ending at 29
        myVar = rand() % n + 1;//prints random number sale ranging from 1 to n for each employee but needs to print once for a random employee ranging from 1 to n. And should print zeros for the rest of the employees. 
        printf("\t%d\n", myVar);
    }

    return 0;
}

5 个答案:

答案 0 :(得分:1)

随机数生成的代码位于运行31次的循环内。

for (c = 0; c<=30; c++)   //c = 0 to 31 -> runs 31 times
{
  myVar = rand() % n + 1;
  printf("%d\n", myVar);
}

如果您希望仅生成一次随机数,请删除for loop

答案 1 :(得分:0)

myVar = rand() % n + 1;

这是在一个运行30次的for循环中

答案 2 :(得分:0)

你想做什么? 如果您只想省略for循环,那么只打算打印一次数字:

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

int main (void)
{
int n,c;
srand(time(NULL));
int myVar;

printf("Enter the number of sales to simulate: ");
scanf("%d", &n);
while(n<1 || n>10000)//blocking while loop
{
    //prompt user to enter proper number for calculation
    printf("Error: Enter a proper number in the range from 1 to 10000: \a");
    scanf("%d",&n);
}

myVar = rand() % n + 1;
printf("%d\n", myVar);

答案 3 :(得分:0)

问题是你正在使用for循环,在该范围内创建31个(自c = 0 ; c <= 30)个随机数并打印全部31个。如果你只想打印1个随机数,只需删除for循环。您实际上在此代码中不需要myVar。您可以直接打印随机数而不存储它。这就是

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

int main (void)
{
int n;
srand(time(NULL));


printf("Enter the number of sales to simulate: ");
scanf("%d", &n);
while(n<1 || n>10000)//blocking while loop
{
    //prompt user to enter proper number for calculation
    printf("Error: Enter a proper number in the range from 1 to 10000: \a");
    scanf("%d",&n);
}

    // Removed the for loop and now only one random number is found

    printf("%d\n", rand() % n + 1);  // See, no need of a variable

}

另外,我不明白你使用数组是什么意思,所以请详细说明你的想法。

答案 4 :(得分:0)

使用,

srand ( time(NULL) );
number = rand() % 30 + 1;

或者如果想要生成唯一的随机数,请使用github中的urand()lib。