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

How to generate a random number within a range once in C?

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;
}
myVar = rand() % n + 1;

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

你想做什么? 如果您只想打印一次数字,请省略 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);

好吧,问题是你正在使用 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

}

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

生成随机数的代码在运行 31 次的循环中。

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

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

使用,

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

或者如果要生成唯一的随机数,请使用 github.

中的 urand() 库