enter 發表於 2015-3-3 01:16:01

輸入姓名和分數並列出最高和最低

輸入學生的名字和分數,然後找出最高分和最低分的姓名及其分數。

教科書上的寫法:
#include <stdio.h>

int main(void){

char name,*highname,*lowname;
int rate,i,high,low;

printf("Enter name and points:\n");
for(i=0;i<5;i++)
scanf("%s %d",name,&rate);

low=30000;high=0;

for(i=0;i<5;i++)
{
if(rate>high)
{high=rate;
highname=name;}
if(rate<low)
{low=rate;
lowname=name;}
}
printf("High point is %d by %s, and low point is %d by %s.",high,highname,low,lowname);

return 0;
}

我後來自己的寫法,還可以依序排出所有的高低:
#include <stdio.h>

int main(void){

char name,test;
int rate,temp;
int i,j;

for(i=0;i<6;i++)
{
printf("Enter name and rate:\n");
scanf("%s %d",name,&rate);
}

for(i=0;i<6;i++)
for (j=i+1;j<6;j++) //用 j=i+1 才好,如果直接用 i+1 則可能會往後多出一個元素。
    if(rate>rate) {
      temp=rate;
      rate=rate;
      rate=temp;
      
   strcpy(test,name);
   strcpy(name,name);
   strcpy(name,test);
            
}

printf("The high rate is %d by %s, and low rate is %d by %s.\n",rate,name,rate,name);
return 0;
}
頁: [1]
查看完整版本: 輸入姓名和分數並列出最高和最低