下面的程序是使用函数按升序对数字进行排序。它是用 Visual Studio 编写的。
我知道我在函数声明中犯了一个错误,因为我在int LinearSort();
上面声明main
而不是在里面声明main
。
程序执行时没有错误,但由于未调用该函数,因此不会进行排序。
程序保存为 C++。
谁能帮我调用该函数并通过下面的编辑程序进行排序?
主文件
#include <stdio.h>
#include <stdafx.h>
#include "sort.h"
#include <conio.h>
#include <iostream>
int LinearSort();
int main()
{
int sort[50];
int i=0;
int j=0;
int k=0;
int a = 0;
printf("Enter 10 Numbers");
for ( i = 0; i < 10; i++ )
{
scanf_s("%d",&sort[i]);
}
for ( i = 0; i < 10; i++ )
{
printf("%d\n",sort[i]);
}
return 0;
}
.C文件
#include "stdafx.h"
#include "sort.h"
#include <stdio.h>
#include <conio.h>
#include <iostream>
void LinearSort(int i, int j, int k, int a, int sort[])
{
for ( j=0; j < i-1; j++ )
{
for ( k=0; k < i-j-1; k++ )
{
if(sort[k] < sort[k+1])
{
a = sort[k];
sort[k] = sort[k+1];
sort[k+1] = a;
}
else
{
sort[j] = sort[j];
}
}
}
for ( j = 0; j < i; j++ )
{
printf("ascending %d\n",sort[j]);
}
_getch();
}
头文件
#pragma once
#include <stdio.h>
extern void LinearSort(int i, int j, int k, int a, int sort[]);
你走在正确的道路上,你的代码只需要一点点调整。其他人提出了宝贵的建议,其中大部分我不再赘述。
首先定义你的LinearSort()
. 您正在传递一些我们称之为局部变量并且不应传递的变量(i..k)。局部变量仅由您的函数使用并在函数内部声明。正确的定义现在变成:
void LinearSort(int a, int sort[]); // prototype; put in header file or above main
void LinearSort(int a, int sort[]) // function itself
{
int i, j, k; // local variables
然后,在读取所有数据后,您必须从主程序调用它。像这样称呼它:
LinearSort(10, sort[]);
您通过 10 fora
因为您读取了固定数量的整数;如果您读取了任意数字(但小于 50),您将传递一个具有此数量的变量。
供您参考:您传递了数组变量,sort[]
但请注意,此名称sort
在您的 main 和您的函数中是相同的。没有必要,这只是巧合。
至于排序算法,它似乎基于冒泡排序,但使用了 for 循环。那至少是不寻常的,而且可能是错误的;外循环必须根据需要进行多次,直到没有更多的元素被交换;但是,for 循环通常执行固定的次数,所以您会明白为什么这可能是错误的。我建议您阅读有关冒泡排序的内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句