简体   繁体   English

查找数组中最大的函数的麻烦

[英]function trouble about find largest in array

write a program that enter a series of integer(stores in array),then sorts the integer by calling the function selection_sort. 编写一个输入一系列整数(存储在数组中)的程序,然后通过调用函数selection_sort对整数进行排序。 When given an array with n elements, selection_sort must do the following: 1.search the array to find the largest,then move it to the last position. 当给定一个包含n个元素的数组时,selection_sort必须执行以下操作:1.搜索数组以找到最大的数组,然后将其移到最后一个位置。 2.call itself recursively to sort the first n-1 elements of the array. 2.递归调用自身以对数组的前n-1个元素进行排序。

following is my code i think the code is errors everywhere i hope some master can help me 以下是我的代码,我认为代码到处都是错误,希望一些高手可以帮助我

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

You have to compare. 你必须比较。 BUt you are assigned.. BUT,您已分配..

change this if (a[i] = '\\n') { break; } if (a[i] = '\\n') { break; } if (a[i] = '\\n') { break; } to if (a[i] == '\\n') { break; } if (a[i] = '\\n') { break; }if (a[i] == '\\n') { break; } if (a[i] == '\\n') { break; } . if (a[i] == '\\n') { break; }

You should change follows in your code. 您应该在代码中更改以下内容。

1) change your function call.. 2) declare count and i in function.. 3) for taking values in to array,follow other method.. 1)更改函数调用。2)在函数中声明counti )将值放入数组,请遵循其他方法。

Try yourself... 试试看...

Here is the complete code.Basically there are many syntax and logical error in your code. 这是完整的代码。基本上,您的代码中有很多语法和逻辑错误。 Consider this as refer and compare with your original source. 将此视为参考,并与原始来源进行比较。

 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