code.club

標題: 輸入姓名和分數並列出最高和最低 [打印本頁]

作者: enter    時間: 2015-3-3 01:16
標題: 輸入姓名和分數並列出最高和最低
輸入學生的名字和分數,然後找出最高分和最低分的姓名及其分數。

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

int main(void){

char name[5][10],*highname,*lowname;
int rate[5],i,high,low;

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

low=30000;high=0;

for(i=0;i<5;i++)
{
  if(rate[i]>high)
  {high=rate[i];
  highname=name[i];}
if(rate[i]<low)
{low=rate[i];
lowname=name[i];}
}
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[6][5],test[10];
int rate[6],temp;
int i,j;

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

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

printf("The high rate is %d by %s, and low rate is %d by %s.\n",rate[5],name[5],rate[0],name[0]);
return 0;
}





歡迎光臨 code.club (http://code.club/) Powered by Discuz! X3.2