##题目: 给定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
代码:
c语言版结构体版:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 #include <stdio.h> #include <string> struct Book { char name[30 ]; double price; }; int main (void ) { int n; int min,max; scanf ("%d" ,&n); getchar (); Book books[n]; gets (books[0 ].name); scanf ("%lf" ,&books[0 ].price); max=0 ; min=0 ; for (int i=1 ;i<n;i++){ getchar (); gets (books[i].name); scanf ("%lf" ,&books[i].price); if (books[i].price>books[min].price){ max=i; } if (books[i].price<books[min].price){ min=i; } } printf ("%.2lf, %s\n" ,books[max].price,books[max].name); printf ("%.2lf, %s\n" ,books[min].price,books[min].name); return 0 ; }
c语言普通版(不用结构体)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 #include <stdio.h> #include <string.h> int main (void ) { int n; double minprice,maxprice; char maxname[30 ],minname[30 ]; char name[30 ]; double price; scanf ("%d" ,&n); getchar (); gets (name); scanf ("%lf" ,&price); maxprice=price; minprice=price; strcpy (maxname,name); strcpy (minname,name); for (int i=1 ;i<n;i++){ getchar (); gets (name); scanf ("%lf" ,&price); if (price>maxprice){ maxprice=price; strcpy (maxname,name); } if (price<maxprice){ minprice=price; strcpy (minname,name); } } printf ("%.2lf, %s\n" ,maxprice,maxname); printf ("%.2lf, %s\n" ,minprice,minname); return 0 ; }
c++版:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 #include <iostream> #include <string> #include <iomanip> using namespace std;struct Book { string name; double price; }; int main (void ) { int n; int min=0 ,max=0 ; cin>>n; getchar (); Book books[n]; getline (cin,books[0 ].name); cin>>books[0 ].price; max=0 ; min=0 ; for (int i=1 ;i<n;i++){ getchar (); getline (cin,books[i].name); cin>>books[i].price; if (books[i].price>books[min].price){ max=i; } if (books[i].price<books[min].price){ min=i; } } cout<<setiosflags (ios::fixed)<<setprecision (2 )<<books[max].price<<", " <<books[max].name<<endl; cout<<setiosflags (ios::fixed)<<setprecision (2 )<<books[min].price<<", " <<books[min].name<<endl; return 0 ; }
c语言版: