簡體   English   中英

程序使用數組打印最小n個數字的位置

[英]program to print the position of the smallest number of n numbers using arrays

當我在數組中輸入值1時,此代碼沒有給我答案。 因為例如我沒有。 的元素數為5,然后我將它們輸入為2、3、1、6、4,然后輸出給出2,因為最小的數字和位置數字並不總是正確的。這是什么錯誤?

#include<stdio.h>
int main()
{
    int n,i,a[10],sum=0;
    int small=0,pos=0;
    printf("enter no of elements in array:");
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        printf("a[%d]=",i);
        scanf("%d",&a[i]);
    }
    for(i=1;i<n;i++)
    {
        small=a[0];
        if( a[i] < small)
        {
            small=a[i];
            pos=i;
        }
    }
    printf("smallest no:%d \n",small);
    printf("position:%d",pos);

}

在每次迭代中,“小”變量均被a [0]覆蓋。 只需將其移出循環即可:

#include<stdio.h>

int main()
{
    int n,i,a[10],sum=0;
    int small=0,pos=0;
    printf("enter no of elements in array:");
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        printf("a[%d]=",i);
        scanf("%d",&a[i]);
    }
    small=a[0];
    for(i=1;i<n;i++)
    {
        if( a[i] < small)
        {
            small=a[i];
            pos=i;
        }
    }
    printf("smallest no:%d \n",small);
    printf("position:%d",pos);

}

您並不遙遠-使用正在初始化small=a[0]; 每當循環迭代時,只需初始化small=a[0]; 在此之前,循環

   #include<stdio.h>
    int main()
    {
        int n,i,a[10],sum=0;
        int small=0,pos=0;
        printf("enter no of elements in array:");
        scanf("%d",&n);
        for(i=0;i<n;i++)
        {
            printf("a[%d]=",i);
            scanf("%d",&a[i]);
        }
small=a[0];
        for(i=1;i<n;i++)
        {

            if( a[i] < small)
            {
                small=a[i];
                pos=i;
            }
        }
        printf("smallest no:%d \n",small);
        printf("position:%d",pos);

    }

small = a [0]應該在循環之前。

您應該在for循環開始之前編寫small = a[0]

暫無
暫無

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

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