在C中编程在随机数组中找到最小值?

时间:2015-09-28 01:08:17

标签: c arrays algorithm

我程序的一部分用于输出随机数存储的数组中的最小值和最大值。我的程序输出数组中的最大值就好了但是当输出最小值时,它会输出一些垃圾。我搜索了网站,我认为根据我发现的情况,它应该可以正常工作。这是我的代码,我很感激帮助!

#include <stdio.h>
#include <stdlib.h>  
#include <time.h>  

int main(void){
    int randomNumbers[100];
    double average;
    int highest, smallest;
    int sum = 0;
    int i = 0;
    int min, max;
    srand(time(NULL));       
    printf("Enter min and max respectively: ");
    scanf("%d %d", &min, &max);
    smallest = highest = randomNumbers[0];
    for (i; i < 100; i++){
        randomNumbers[i] = rand() % (max - min + 1) + min; 
        sum = sum + randomNumbers[i];

        if (highest < randomNumbers[i]){
            highest = randomNumbers[i];
        }

        if (smallest > randomNumbers[i]){
            smallest = randomNumbers[i];
        }

        printf("%d ", randomNumbers[i]);
        if (i == 9 || i == 19 || i == 29 || i == 39 || i == 49 || i ==59 || i == 69 || i ==79 || i == 89)
            printf("\n");

    } 
    average = sum / 100;
    printf("\nAverage: %lf", average);
    printf("\nHighest: %d", highest);
    printf("\nSmallest: %d", smallest);

}

1 个答案:

答案 0 :(得分:2)

问题是你的初始化:

GET <url>/user //points to index() method on UserController
GET <url>/user/create //points to create() method on UserController
POST <url>/user //points to store() method on UserController
POST <url>/user/{userid}/edit //points to edit(userId) method on UserController

smallest = highest = randomNumbers[0]; 尚未填充。如果您首先填充所有数字可能会更清楚。