【发布时间】:2015-03-03 07:08:31
【问题描述】:
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;
}
【问题讨论】:
-
检查How to generate a random number in C?。还有随机数范围的答案。
-
好的,现在说明你的具体问题是什么(提供更多细节)。
-
我正在尝试将随机数提供给随机员工 (0-30)。其余员工得零。这就是我使用 for 循环的原因。但它给每个员工一个随机数。那是我的问题
-
所以,你想给一个随机的员工一个随机数并给其余的 0,但是你的代码给了每个员工一个随机数。那是对的吗 ?您必须发布其余代码,以便我们更好地理解并帮助您编写代码。
-
是的,就是这样
标签: c arrays random range srand