输入五个国家名称排序
时间: 2024-02-19 09:59:14 浏览: 51
好的,以下是使用 C++ 语言编写的实现代码:
```cpp
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
string countries[5];
// 输入国家名称
cout << "请输入五个国家名称:" << endl;
for (int i=0; i<5; i++) {
cin >> countries[i];
}
// 对国家名称进行排序
sort(countries, countries+5);
// 输出排序后的结果
cout << "排序后的结果为:" << endl;
for (int i=0; i<5; i++) {
cout << countries[i] << endl;
}
return 0;
}
```
运行程序后,会提示您输入五个国家名称,依次输入后,程序会使用 `sort()` 函数对这些名称进行排序,最后输出排序后的结果。
例如,您输入的五个国家名称分别为:美国、中国、俄罗斯、日本、韩国,则程序输出的结果为:
```
排序后的结果为:
中国
俄罗斯
日本
美国
韩国
```
其中,中国排在第一位,韩国排在最后一位。
希望能够帮到您!
相关问题
编程c语言 任意输入五个国家的名字按从小到大排序
以下是一个简单的 C 代码示例,用于按照国家的面积大小进行排序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 比较函数,用于排序
int cmp(const void* a, const void* b, void* data) {
double* areas = (double*)data;
const char** countries = (const char**)data + 5;
int idx_a = -1, idx_b = -1;
for (int i = 0; i < 5; i++) {
if (strcmp(countries[i], *(const char**)a) == 0) {
idx_a = i;
}
if (strcmp(countries[i], *(const char**)b) == 0) {
idx_b = i;
}
}
return areas[idx_a] < areas[idx_b] ? -1 : 1;
}
int main() {
const char* countries[5];
double areas[5];
for (int i = 0; i < 5; i++) {
printf("请输入第 %d 个国家的名字:", i+1);
countries[i] = (char*)malloc(sizeof(char) * 20); // 假设国家名字不超过 20 个字符
scanf("%s", (char*)countries[i]);
printf("请输入第 %d 个国家的面积:", i+1);
scanf("%lf", &areas[i]);
}
// 排序
qsort((void*)countries, 5, sizeof(char*), cmp, (void*)areas);
// 输出排序结果
printf("按照面积从小到大排序结果:\n");
for (int i = 0; i < 5; i++) {
printf("%s\n", countries[i]);
}
// 释放内存
for (int i = 0; i < 5; i++) {
free((void*)countries[i]);
}
return 0;
}
```
运行程序后,按照提示输入五个国家的名字和面积,程序将按照面积从小到大的顺序输出国家的名字。
如果你想按照国家的人口数量进行排序,只需要将 `areas` 数组换成人口数量的数组,并修改比较函数即可。
用C语言输入十个国家的名字按从小到大排序
可以使用冒泡排序法来实现:
```c
#include <stdio.h>
#include <string.h>
#define MAX_COUNTRY_NAME_LENGTH 50
#define NUMBER_OF_COUNTRIES 10
int main() {
char countries[NUMBER_OF_COUNTRIES][MAX_COUNTRY_NAME_LENGTH];
int i, j;
char temp[MAX_COUNTRY_NAME_LENGTH];
// 输入国家名字
printf("请输入%d个国家名字:\n", NUMBER_OF_COUNTRIES);
for (i = 0; i < NUMBER_OF_COUNTRIES; i++) {
scanf("%s", countries[i]);
}
// 冒泡排序
for (i = 0; i < NUMBER_OF_COUNTRIES - 1; i++) {
for (j = 0; j < NUMBER_OF_COUNTRIES - 1 - i; j++) {
if (strcmp(countries[j], countries[j+1]) > 0) {
strcpy(temp, countries[j]);
strcpy(countries[j], countries[j+1]);
strcpy(countries[j+1], temp);
}
}
}
// 输出排序结果
printf("排序结果为:\n");
for (i = 0; i < NUMBER_OF_COUNTRIES; i++) {
printf("%s\n", countries[i]);
}
return 0;
}
```
上述代码中,我们首先定义了两个常量 `MAX_COUNTRY_NAME_LENGTH` 和 `NUMBER_OF_COUNTRIES`,分别表示国家名字的最大长度和输入的国家数量。然后定义了一个二维字符数组 `countries` 来存储国家名字,以及一个临时字符数组 `temp` 用于交换两个国家名字。
接着,我们使用 `scanf` 函数输入每个国家的名字,然后使用冒泡排序算法对这些名字进行从小到大的排序。排序过程中,我们使用 `strcmp` 函数来比较两个字符串的大小关系,并使用 `strcpy` 函数来交换两个字符串的值。
最后,我们输出排序结果即可。