我有这个代码的问题,因为当我运行它时,我得到一个数字随机生成器的无限循环。我想要做的是分配给数组,从1到9的99个数字,然后进行一些数学简单的操作。生成一个范围内的随机整数(无限循环)
#include <stdio.h>
#include <stdlib.h>
#define SIZE 99
void mean(const int a[]);
void median(int a[]);
void mode(int freq[] , const int a[]);
int main (void) {
int response[SIZE];
int frequency [10];
int i;
srand(time(NULL));
for (i = 0; i<= SIZE ; i++) {
response[i] = (rand() % 6) +1 ;
printf("%d", response[i]);
}
mean(response);
median(response);
mode(frequency , response);
return 0;
}
void mean(const int a[]){
int j , total = 0;
float mean;
printf("********\n%6s\n********\n\nThe mean is the average value of the data\nitems.", "Mean");
printf("The mean is equal to the total of\n all the data items");
printf("divided by the number\n of data items (%d):", SIZE);
for(j = 0 ; j <= SIZE ; j++){
total += a[j];
}
mean = (float) total/SIZE;
printf("The mean value for\nthis run is %d/%d = %f", total, SIZE, mean);
}
void median(int a[]){
int i, j, n, median, hold;
n=1;
hold = 0;
printf("********\n%7s\n********\n\nThe unsorted array of responses is\n", "Median");
for (i=0;i<=SIZE;i++){
if ((i/10) <= n){
printf("%d", a[i]);
}
else{
printf("\n");
n++;
}
}
printf("The sorted array is\n");
for(i=0;i<=SIZE;i++){
for(j=0;j<=SIZE-1;j++){
if (a[j]>a[(j+1)]){
hold = a[j];
a[j] = a[ (j + 1)];
a[ (j + 1)] = hold;
}
}
if ((i/10) <= n){
printf("%d", a[i]);
}
else{
printf("\n");
n++;
}
}
median = a[SIZE/2];
printf("The median is element %d of\nthe stored %d element array.\n", SIZE/2 , SIZE);
printf("For this run the median is %d", median);
}
void mode (int freq [] , const int a[]){
int j, o, mode , i, rating;
printf("********\n%6s\n********\n\n%10s%12s%12s", "Mode" ,"Response" ,"Frequency", "Histogram");
for(j=0; j<= SIZE ; j++){
++freq[a[j]];
}
for (i=0 ; i <= 10 ; i++){
printf("%10d%12d ", i, freq[i]);
for (o=0; o<=freq[i];o++){
printf("*");
}
printf("\n");
if (freq[i] > freq[i+1]){
mode = freq[i];
rating = i;
}
}
printf("The mode is the most frequent value.\n");
printf("For this run the mode is %d which occured %d times", rating ,mode);
}
为什么'rand()%6'当你想要1到9之间的数字。它应该是'rand()%9 + 1' ... – ShuklaSannidhya
注意[modulo bias](http:// stackoverflow .COM /问题/ 10984974 /为什么-DO-人说,有 - 是 - 模偏置时 - 使用 - 一个随机数发生器?LQ = 1)。 –
'frequency'数组应该在'mode'函数的本地。你不要在别的地方使用它。在main中声明并将其传递给'mode'没有意义。相反,将它声明为'mode'的本地。 – ShuklaSannidhya