以下内容应该有所帮助 - 它解决了循环索引的问题(从 0 到 9,而不是 1 到 10),并生成 10 到 20 之间的随机数。有一个小错误 - 使用你得到的模数运算符分布非常轻微的不均匀。如果您足够关心,您可以创建一个消除上述随机数的函数,例如 32758。那么它将是“完全公平的”。
编辑我已经修改了这个程序,所以它被分成了许多函数——一个生成数组,另一个打印数组,第三个取数组的平均值。它还包括一个自定义函数,可以进行“公平”随机分布。我想你的教授会认为你有帮助(如果他用谷歌搜索代码中的任何短语,他会登陆这个页面)。所以以此为灵感,然后编写自己的代码。从例子中学习是好的;抄袭不好。
EDIT 修改了fillArray 函数。现在使用在主程序中分配的空间,而不是在函数本身中创建空间。简单一点。
#include <stdio.h>
#include <stdlib.h>
// function declarations
int* fillArray(int* a, int n, int llim, int ulim);
float arrayAverage(int *a, int nElements);
void arrayPrint(int *a, int n);
int fairRand(int, int);
int main(int argc, char* argv[]) {
int m[10];
float av;
m = fillArray(m, 10, 10, 20); // note that 'm' is a pointer (int*) to the array m[]
av = arrayAverage(m, 10);
arrayPrint(m, 10);
printf("The average is %.2f\n", av);
return 0;
}
int* fillArray(int *a, int n, int llim, int ulim) {
// given an array a with size n
// fill each element in the array with a random element
// between llim and slim (inclusive)
int i;
for ( i = 0; i < n; i++ )
{
a[ i ] = fairRand(llim, ulim); // calling our user-defined function
}
return a;
}
float arrayAverage(int *a, int n) {
// returns the sum of values in a[n] divided by n
int j;
double s=0.0;
for (j = 0; j < n; j++ )
{
s += a[j];
}
return (float)(s / (double) n);
}
void arrayPrint(int *a, int n) {
// prints each element in the array m[n]
int j;
for (j = 0; j < n; j++ )
{
printf("Element[%d] = %d\n", j, a[j] );
}
}
int fairRand(int a, int b) {
// generates fair random number between a and b, inclusive
int diff = b - a + 1;
int r;
int largest = diff * (RAND_MAX / diff);
// this is the "magic" line: keep generating random numbers
// until the number generated fits in the interval that has equal number
// of each possible value after the modulo operation:
while( (r = rand()) >= largest) {
// keep going around...
} ;
// we now have a "fair" random number r
return a + r % diff;
}