簡體   English   中英

用於查找數組中最小元素的 for 循環

[英]for loop for finding smallest element in an Array

好的,所以我的程序假設創建一個數組大小 [8],然后一旦打印出來,我就使用 For 循環來查找數組中的最小數字。 我遇到的問題是它似乎總是停在第二個元素處並將其聲明為最小。 誰能告訴我我的代碼有什么問題

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


void main(int argc, char* argv[])
{
const int len = 8;
int a[len];
int i;



srand(time(0));

//Fill the array
for(i = 0; i < len; ++i) {
    a[i] = rand() % 100;
}

//Print the array
for (i = 0; i < len; ++i) {
    printf("%d ", a[i]);
}
printf("\n");
getchar();

int smallest;
for (i = 1; i < len; i++) {
    if (a[i] < smallest)
        smallest = a[i];
    {
        printf("The smallest integer is %d at position %d\n", a[i], i);
        break;
        getchar();

    }
}
}
{
    printf("The smallest integer is %d at position %d\n", a[i], i);
    break;
    getchar();

}

該塊與if條件同時執行,這意味着一旦遇到小於smallesta[i] ,您就會跳出循環。

順便說a[0] ,您可能希望在進入循環之前將smallest初始化為等於a[0]

Int smallest=a[0];
for (int i=1;i<len;i++)
{
     if(a[i]<smallest)
           Smallest=a[i];
}

您的代碼中有一些錯誤,如下所示:

1-在初始化之前使用變量int minimum。 2- last for 循環內部的邏輯是錯誤的。

正確的代碼是:

void main(int argc, char* argv[])
{
    const int len = 8;
    int a[len];
    int smallest;
    int location =1;
    int i;

    srand(time(0));

    //Fill the array
    for(i = 0; i < len; ++i) 
    {
       a[i] = rand() % 100;
    }

    //Print the array
    for (i = 0; i < len; ++i)
    {
      printf("%d ", a[i]);
    }
    printf("\n");

    smallest = a[0];

    for ( i= 1 ; i < len ; i++ ) 
    {
        if ( a[i] < smallest ) 
        {
           smallest = a[i];
           location = i+1;
        }
    } 
    printf("Smallest element is present at location %d and it's value is %d.\n",      location,    smallest );

    getch();
}

暫無
暫無

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

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