【问题标题】:I'm trying to write a sort function in C but I'm pretty new at declaring functions and couldn't make it work我正在尝试用 C 编写一个排序函数,但我在声明函数方面还很陌生,无法让它工作
【发布时间】:2021-06-26 20:12:03
【问题描述】:

我正在学习如何在 C 中声明函数并使用它们。我尝试在 C 中编写砖排序算法,但无法使其工作。当我在主函数中编写所有内容时,算法本身运行良好,所以我认为问题在于我如何尝试声明函数。正如我所说,我是这方面的新手,所以如果我明显遗漏了一些东西,请原谅我,并提前感谢您抽出时间帮助我。我真的很感激。

这是我的代码

#include <stdio.h>

int n, i, a[100], temp, isSorted;

int brickSort(a[], n)
{
    isSorted=0;
    
    while(isSorted==0)
    {
        isSorted=1;
        
        for(i=0; i<=n-2; i=i+2)
        {
            if(a[i]>a[i+1])
            {
                temp=a[i];
                a[i]=a[i+1];
                a[i+1]=temp;
                isSorted=0;
            }
        }
        
        for(i=1; i<=n-2; i=i+2)
        {
            if(a[i]>a[i+1])
            {
                temp=a[i];
                a[i]=a[i+1];
                a[i+1]=temp;
                isSorted=0;
            }
        }
    }
    
    for(i=0; i<n; i++)
    {
        printf("%d ", a[i]);
    }
}

int main()
{
    printf("Enter the amount of numbers ");
    scanf("%d", &n);
    
    for(i=0; i<n; i++)
    {
        printf("Enter number ");
        scanf("%d", &a[i]);
    }
    
    return brickSort(a[], n);

    return 0;
}

这是我收到的错误消息

 int brickSort(a[], n)
               ^
main.c:5:20: error: expected declaration specifiers or ‘...’ before ‘n’
 int brickSort(a[], n)
                    ^
main.c: In function ‘main’:
main.c:53:12: warning: implicit declaration of function ‘brickSort’ [-Wimplicit-function-declaration]
     return brickSort(a[], n);
            ^~~~~~~~~
main.c:53:24: error: expected expression before ‘]’ token
     return brickSort(a[], n);
                        ^

【问题讨论】:

标签: c function


【解决方案1】:

您必须指定参数的类型来声明参数,例如:

int brickSort(int a[], int n)

并从函数调用中删除额外的[],例如:

return brickSort(a, n);

在这种情况下,所有变量都被声明为全局变量(不是好的设计),所以你实际上不需要参数,你可以像这样删除它们:

int brickSort(void)
return brickSort();

【讨论】:

    【解决方案2】:

    你必须把参数的类型放在参数列表中。

    int brickSort(int a[], int n)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-23
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      相关资源
      最近更新 更多