簡體   English   中英

在整數數組中找到最小的數字

[英]Finding the smallest number in an array of integers

我編寫了一個小程序,該程序從用戶那里獲取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;
}


我已經更新了我的代碼。 現在,我在for循環之前初始化臨時值。 但是它仍然無法正常工作。

如果您只想打印出數組的最小元素,這是最基本的方法:

#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;
}

最少的代碼量必須使用LINQ:

var example_arr = new [] {3,49, 12, 11, 78, 1};
var smallest = example_arr.Select(t=>t).Concat(new[]{INT_MAX}).Min();

您將在循環的每次迭代中重新初始化temp變量。

您應該將當前的最小數字存儲在循環外部 (初始化為數組的第一個元素),並進行檢查。

temp1變量必須在循環外使用非常大的值(例如INT_MAX )初始化。

如果您只想返回最小的數字,請不要對數組進行排序。

無論如何,

  • 在第一次迭代中,將數組的第一個元素放在索引-1中(在C語言中為“合法”,但這不是您想要的...):intarray [i-1] = intarray [i]。 您應該從1開始循環。

  • 您會在每次迭代時都使用temp1的值(因為您在循環內將其初始化為0)。 我建議您在循環外對其進行初始化。

順便說一句,如果您在循環之前將變量temp1初始化為intarry [0](而不是0),則也將支持負數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM