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;
}
最佳答案
随机数生成的代码位于运行 31 次的循环内。
for (c = 0; c<=30; c++) //c = 0 to 31 -> runs 31 times
{
myVar = rand() % n + 1;
printf("%d\n", myVar);
}
如果您希望随机数仅生成一次,请删除 for 循环
。
关于c - 如何在C中生成一次范围内的随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28825981/