【问题标题】:function trouble about find largest in array关于在数组中查找最大的函数问题
【发布时间】:2014-12-27 08:25:55
【问题描述】:

编写一个程序,输入一系列整数(存储在数组中),然后通过调用函数 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;
}

【问题讨论】:

  • 您的代码有语法错误。 selection_sort 如何看到 count?此外,您的逻辑a[i] == '\n' ) 有缺陷。 a[i] 永远不会是 '\n'。此外,您正在使用selection_sort 中的起始索引1 访问数组。那必须是0
  • codeSmellHomework++; // 咧嘴一笑

标签: c arrays function


【解决方案1】:

你必须比较。但是你被分配了..

将此if (a[i] = '\n') { break; } 更改为if (a[i] == '\n') { break; }

您应该在代码中更改以下内容。

1) 改变你的函数调用.. 2)在函数中声明counti.. 3) 要将值放入数组,请按照其他方法..

自己试试……

【讨论】:

  • int main(void) { int a[100] = { 0 },i=0,count=0; while (1) { scanf("%d",&a[i]); if (a[i] == '\n') { 中断; } 我++;计数++; } printf("%d", a[2]);返回0; }
  • 我用它来调试,但它不会坏
  • 好的。我有课,等我回来试试
【解决方案2】:

这是完整的代码。基本上你的代码中有很多语法和逻辑错误。将此视为参考并与您的原始来源进行比较。

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

【讨论】:

  • 谢谢你的帮助,我会和我的后者比较,我应该去calss。
  • 如果我也有问题,我仍然需要你的帮助。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-03
  • 2013-11-28
相关资源
最近更新 更多