本文主要是介绍C //例6.3 有10个地区的面积,要求对它们按由小到大的顺序排列。,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
C语言设计 (第四版) 谭浩强 例6.3
例6.3 有10个地区的面积,要求对它们按由小到大的顺序排列。
IDE工具:VS2010
Note: 使用不同的IDE工具可能有部分差异。
代码块
方法1:使用冒泡排序
#include <stdio.h>
#include <stdlib.h>int main(){int area[10];printf("Enter 10 area: ");for(int i = 0; i < 10; i++){printf("Enter No.%d area: ", i + 1);scanf("%d", &area[i]);while(area[i] <= 0){printf("Error! Area cannot be less than or equal to 0! Retry!\n");printf("Enter No.%d area: ", i + 1);scanf("%d", &area[i]);}}int temp;for(int i = 0; i < 9; i++){for(int j = 0; j < 10; j++){if(area[j] > area[i]){temp = area[j];area[j] = area[i];area[i] = temp;}}}printf("Sort by area in ascending order: ");for(int i = 0; i < 10; i++){printf("%d ", area[i]);}printf("\n");system("pause");return 0;
}
方法2:使用指针、函数指针、冒泡排序、选择排序和函数的模块化设计
#include <stdio.h>
#include <stdlib.h>#define N 10void inputArea(int *area, int n){for(int i = 0; i < n; i++){printf("Enter No.%d area: ", i + 1);scanf("%d", &area[i]);while(area[i] <= 0){printf("Error! Area cannot be less than or equal to 0! Retry!\n");printf("Enter No.%d area: ", i + 1);scanf("%d", &area[i]);}}
}//冒泡排序
void bubbleSortAscending(int *area, int n){int temp;for(int i = 0; i < n - 1; i++){for(int j = 0; j < n - 1 - i; j++){if(area[j] > area[j+1]){temp = area[j];area[j] = area[j+1];area[j+1] = temp;}}}printf("Bubble Sort:\n");
}//选择排序
void selectionSortAscending(int *area, int n){int temp;for(int i = 0; i < n - 1; i++){for(int j = i + 1; j < n; j++){if(area[i] > area[j]){temp = area[i];area[i] = area[j];area[j] = temp;}}}printf("Selection Sort:\n");
}void output(int *area, int n){printf("Sort by area in ascending order: ");for(int i = 0; i < 10; i++){printf("%d ", area[i]);}printf("\n");
}int main(){int *area = (int*)malloc(N * sizeof(int));void (*funChoose[2])(int *, int) = {bubbleSortAscending, selectionSortAscending};inputArea(area, N);int *method[2] = {area, area};for(int i = 0; i < 2; i++){funChoose[i](method[i], N);output(method[i], N);}free(area);system("pause");return 0;
}
这篇关于C //例6.3 有10个地区的面积,要求对它们按由小到大的顺序排列。的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!