查找整数数组中的最小数字

Ord*_*rdo 1 c

我编写了一个小程序,它从用户那里获取5个数字并将它们存储在一个整数数组中.该数组被传递给一个函数.该函数用于查找数组中的最小数字并将其打印出来.由于输出不正确,我不知道为什么.该函数总是打印出数组的第一个元素,它应该是最小的数字,但事实并非如此.

#include <stdio.h>

void smallestint (int intarray [], int n)

{
    int i;
    int temp1 = 0;
    int temp2 = 0;

    for(i = 0; i < n; i ++)
    {

        if (intarray [i] < temp1)
        {
            intarray [i-1] = intarray [i];
            temp2 = intarray[i];
            intarray[i] = temp1;
            temp1 = temp2;
        }
        else 
            temp1 = intarray[i];
    }

    printf("%d\n", intarray[0]);
}

int main ()

{
    const int n = 5;
    int temp = 0;
    int i;
    int intarray [n];

    printf("Please type in your numbers!\n");

    for(i = 0; i < n; i ++)
    {
        printf("");
            scanf("%d", &temp);         
        intarray[i] = temp;

    }

    smallestint (intarray, n);


    getchar();
    getchar();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)


我已经更新了我的代码.现在我在for循环之前初始化临时值.但它仍然无法正常工作.

Jim*_*som 8

如果您只想打印出数组中最小的元素,这是最基本的方法:

#include <limits.h>
#include <stdio.h>

int smallest(int* values, int count)
{
        int smallest_value = INT_MAX;
        int ii = 0;
        for (; ii < count; ++ii)
        {
                if (values[ii] < smallest_value)
                {
                        smallest_value = values[ii];
                }
        }
        return smallest_value;
}

int main()
{
        int values[] = {13, -8, 237, 0, -3, -1, 15, 23, 42};
        printf("Smallest value: %d\n", smallest(values, sizeof(values)/sizeof(int)));
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 几乎正是我所暗示的,减去INT_MAX部分. (3认同)