设计思路:
通过计算发现,购买时只需按(x*5+y)(0<y<5),x套5本另外买y本(0<y<5)时价格最低,但是其中有一个列外,在x*5+2*4的情况这,按x套5本,2套4本购买比x套5本另外买y本便宜。所以便可以通过情况分析编程。
程序代码:
1 #include <iostream> 2 using namespace std; 3 4 void main() 5 { 6 int x; 7 cout << "请输入要购买的本数:" << endl; 8 cin >> x; 9 10 int i; 11 i = x/5; 12 13 if (x < 5) 14 { 15 switch(x) 16 { 17 case 1: 18 cout << "买1本书最低价格为8元"<< endl; 19 break; 20 case 2: 21 cout << "买2本书最低价格为" << x*8*0.95 << "元"<< endl; 22 break; 23 case 3: 24 cout << "买3本书最低价格为" << x*8*0.9 << "元"<< endl; 25 break; 26 case 4: 27 cout << "买4本书最低价格为" << x*8*0.8 << "元"<< endl; 28 } 29 } 30 else{ 31 switch(x%5) 32 { 33 case 0: 34 cout << "买" << i << "套5本的" << endl; 35 cout << "最低价格为:" << i*8*5*0.75<< endl; 36 break; 37 case 1: 38 cout << "买" << i << "套5本的" << endl; 39 cout << "外加" << x%5 << "本" << endl; 40 cout << "最低价格为:" << i*8*5*0.75 + (x%5)*8<< endl; 41 break; 42 case 2: 43 cout << "买" << i << "套5本的" << endl; 44 cout << "外加" << x%5 << "本" << endl; 45 cout << "最低价格为:" << i*8*5*0.75 + (x%5)*8*0.95 << endl; 46 break; 47 case 3: 48 cout << "买" << i-1 << "套5本的" << endl; 49 cout << "外加2套4本" << endl; 50 cout << "最低价格为:" << (i-1)*8*5*0.75 + 2*4*8*0.8 << endl; 51 break; 52 case 4: 53 cout << "买" << i << "套5本的" << endl; 54 cout << "外加" << x%5 << "本" << endl; 55 cout << "最低价格为:" << i*8*5*0.75 + (x%5)*8*0.8 << endl; 56 } 57 } 58 }
结果截图:
个人总结:
这道题挺简单的,但是怎样更简单的做出来才是最好的。通过分析,最后选择了这个方法。感觉还是这样简单。
时间: 2024-10-27 06:49:07