查找書籍 (20 分)
給定n本書的名稱和定價,本題要求編寫程序,查找並輸出其中定價最高和最低的書的名稱和定價。
輸入格式:
輸入第一行給出正整數n(<10),隨後給出n本書的信息。每本書在一行中給出書名,即長度不超過30的字符串,隨後一行中給出正實數價格。題目保證沒有同樣價格的書。
輸出格式:
在一行中按照“價格, 書名”的格式先後輸出價格最高和最低的書。價格保留2位小數。
輸入樣例:
3
Programming in C
21.5
Programming in VB
18.5
Programming in Delphi
25.0
輸出樣例:
25.00, Programming in Delphi
18.50, Programming in VB
注:1.按第一種代碼的方法 ,有兩個測試點錯誤,比較兩者,發現我沒有用數組將它盛放後查找,而題目中有查找並輸出這個描 述,猜測是因爲這個原因代碼不能ac
2.先輸入個數後,又輸入了一個回車,需要getchar();將回車吃掉,否則後來的字符輸入會見到回車停止輸入
#include<stdio.h>
struct book{
char name[100];
double price;
};
int main(){
int x,i;
struct book s1,max,min;
scanf("%d",&x);
for(i=0;i<x;i++){
getchar();
scanf("%s",s1.name);
scanf("%lf",&s1.price);
if(i==0){
min=s1;
max=s1;
}
if(max.price<s1.price){
max=s1;
}
if(min.price>s1.price){
min=s1;
}
}
printf("%.2lf, %s\n",max.price,max.name);
printf("%.2lf, %s\n",min.price,min.name);
return 0;
}
#include<stdio.h>
#include<string.h>
struct book{
char name[31];
double price;
}b[10];
int main(){
int n,i,j,mini=0,maxi=0;
double min=1000000,max=-1;
scanf("%d",&n);
for(i=0;i<n;i++){
getchar();
gets(b[i].name); //分行輸入不用加\n
scanf("%lf",&b[i].price);
if(b[i].price>max){
max=b[i].price;
maxi=i; //引用一個新變量來標記最值
}
if(b[i].price<min){
min=b[i].price;
mini=i;
}
}
printf("%.2lf, %s\n",b[maxi].price,b[maxi].name);
printf("%.2lf, %s\n",b[mini].price,b[mini].name);
return 0;
}