【C语言小练习】 任意输入N个数,输出其由大到小的数据。 注意:使用了动态数组来存储数据。 #include <stdio.h> #include <stdlib.h> #include <conio.h> //插入函数 void Insert( int newNum, int **arr, unsigned int *arrLengthIn ); //排序函数 void Sort_BigToSmall( int *arr, unsigned int arrLengthIn ); //处理输入函数 void InputDatas( int **arr, unsigned int *arrLengthIn ); //输出函数 void OutputDatas( int *arr, unsigned int arrLengthIn ); int main( void ) { //1.初始化数据 int *arr = 0; unsigned int arrLength = 0; //2.输入数据 InputDatas( &arr, &arrLength ); //3.从大到小,排序 Sort_BigToSmall( arr, arrLength ); //4.输出数据 OutputDatas( arr, arrLength ); //End printf( "/r/n运行结束。按任意键退出。/r/n" ); getch(); return 0; } void Insert( int newNum, int **arr, unsigned int *arrLengthIn ) { //使用动态数组 (*arrLengthIn)++; if( (*arr) == 0 ) { *arr = (int *)malloc( sizeof(int) ); } else { *arr = (int *)realloc( (void *)(*arr), sizeof(int) * (*arrLengthIn) ); } *((*arr) + (*arrLengthIn) - 1) = newNum; } void Sort_BigToSmall( int *arr, unsigned int arrLengthIn ) { unsigned int i = 0; unsigned int j = 0; unsigned int length = arrLengthIn - 1; int *currentNum = 0; int *nextNum = 0; int t = 0; //冒泡排序 for( i = 0; i < length; i++ ) { for( j = 0; j < length; j++ ) { currentNum = arr + j; nextNum = arr + j + 1; if( (*currentNum) < (*nextNum) ) { t = (*currentNum); (*currentNum) = (*nextNum); (*nextNum) = t; } } } } void InputDatas( int **arr, unsigned int *arrLengthIn ) { //1.初始化数据 bool inputState = false; int inputCache = 0; //2.处理输入 inputState = true; do { printf( "请输入第%u个数(输入0为结束输入):", ((*arrLengthIn) + 1) ); scanf( "%d", &inputCache ); if( inputCache == 0 ) { inputState = false; } else { Insert( inputCache, arr, arrLengthIn ); } } while ( inputState ); } void OutputDatas( int *arr, unsigned int arrLengthIn ) { unsigned int i = 0; unsigned int length = arrLengthIn; printf( "/r/n数组的值:-----------------/r/n" ); for( i = 0; i < length; i++ ) { printf( "[%u] : %d/r/n", (i + 1), *(arr + i) ); } printf( "/r/n" ); }