C语言问题

由键盘任意输入5个国家的英文名称,按英语词典规律排序后输出。

用C语言代码。谢谢

#include <stdio.h>
#include <string.h>
void main()
{
int i=0;
int j=0;
char countryname[5][20]; //5X20的数组,用于保存国家名称
char temp[20]; //交换时使用
printf("Please input five country's name\n");
//输入5个国家的名字
for(i=0;i<5;i++)
{
printf("please input name for country %d\n",i);
scanf("%s",countryname[i]);
}
//冒泡排序按英语词典规律排序
for(i=1;i<5;i++)
{
for(j=0;j<5-i;j++)
{
if(strcmp(countryname[j],countryname[j+1])>0)
{
strcpy(temp,countryname[j]);
strcpy(countryname[j],countryname[j+1]);
strcpy(countryname[j+1],temp);
}
}
}
printf("The country's after sort is:\n");
//排序后的国家名称
for(i=0;i<5;i++)
{
printf("%s\n",countryname[i]);
}
}
//这段代码经过调试没有问题,明天有面试,写个练练手,祝福我吧!!
温馨提示:答案为网友推荐,仅供参考
第1个回答  2020-05-14
这是一个for语句,根据for语句的形式:for(语句1;语句2;语句3){函数体;}
的执行顺序是:语句1,判断语句2是否成立(非0为真,0为假)函数体,最后是语句3,(£)再进行判断语句2,是否成立,在执行函数体,语句3
,在执行(£)知道条件不满足语句2,跳出循环;如果,语句2是非逻辑表达式,即非判断语句时,循环体内,必有满足条件的跳出语句
break,否则为死循环;
这里的
for(k=1;k+1;k++)
可以这样解释:执行循环for()语句时,初始条件
K=1;之后执行
K+1
(k=2,非0,条件为真继续执行)之后执行函数体for下面花括号{}的内容,之后在执行
K++(K自增1)
所以,明白for()语句的执行顺序就可以明白了,明白了吗?
第2个回答  2008-09-02
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define COUNTRIES 5
#define NAME_MAX_LEN 511
typedef struct {
char name[NAME_MAX_LEN+1];
}CountryName;
int compare(const void*a, const void*b) {
if(strcmp(((CountryName*)a)->name,((CountryName*)b)->name)>=0)
return 1;

return 0;
}
int main(void) {
CountryName countries[COUNTRIES] = {0};
int i;
for(i=0;i<COUNTRIES;i++) {
scanf("%s", countries[i].name);
}
qsort(countries, COUNTRIES, sizeof(CountryName),compare);
for (i=0;i<COUNTRIES;i++) {
printf("%s\n", countries[i].name);
}
}
第3个回答  2008-09-02
楼上你把注释写起 让人家新手明白啊