簡體   English   中英

查找數組中最大的函數的麻煩

[英]function trouble about find largest in array

編寫一個輸入一系列整數(存儲在數組中)的程序,然后通過調用函數selection_sort對整數進行排序。 當給定一個包含n個元素的數組時,selection_sort必須執行以下操作:1.搜索數組以找到最大的數組,然后將其移到最后一個位置。 2.遞歸調用自身以對數組的前n-1個元素進行排序。

以下是我的代碼,我認為代碼到處都是錯誤,希望一些高手可以幫助我

#include <stdio.h>

int selection_sort(int a[])//this function have error that "i"and"count"is undeclared
{
   int max = 0;
   for (i = 1; i <= count; i++)// continuous compare to final
   {
      if (a[i] > max)
      {
         max=a[i];
      }
   }
   a[count] = a[i]; //put the max to last position 
   count--;
}

int main(void)
{
   int a[100] = { 0 },i=0,count=0;
   while (1)
   {
      scanf("%d",&a[i]);
      if (a[i] = '\n') { break; }//this line have error because '\n' not "int" so when i "enter" it would not break 

      i++;   
      count++;   //counting how many integer i scanf
   }

   selection_sort();//call this function (i don't know well about function so i don't known where to put is correct )

   return 0;
}

你必須比較。 BUT,您已分配..

if (a[i] = '\\n') { break; } if (a[i] = '\\n') { break; }if (a[i] == '\\n') { break; } if (a[i] == '\\n') { break; }

您應該在代碼中更改以下內容。

1)更改函數調用。2)在函數中聲明counti )將值放入數組,請遵循其他方法。

試試看...

這是完整的代碼。基本上,您的代碼中有很多語法和邏輯錯誤。 將此視為參考,並與原始來源進行比較。

 int selection_sort(int a[], int count){ 
    int max = 0, i =0;

    for (i = 0; i < count; i++){
        if (a[i] > max)
        {
            max=a[i];
        }
    }

    a[count] = max; 
    count--;

    return 0;
}

int main(void) { 

    int a[100] = { 0 },i=0,count=0;;
    printf ("Enter the total num\n");

    scanf("%d",&count);

    if ( ( count  ) >= (sizeof(a)/sizeof(a[0])) )
    return -1;

    while (i < count){
        scanf("%d",&a[i]);
        i++;   
    }

    selection_sort(a, count);

    printf ("\nmax:%d\n", a [count]);
    return 0;
}

暫無
暫無

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

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