zoukankan      html  css  js  c++  java
  • 课堂练习——寻求买书的最低价格

    1.题目要求 

      书店针对《哈利波特》系列书籍进行促销活动,一共5卷,用编号0、1、2、3、4表示,单独一卷售价8元,。

      具体折扣如下所示:

           本数         折扣

           2           5%

           3           10%

           4           20%

           5           25%

      根据购买的卷数以及本数,会对应不同折扣规则情况。单数一本书只会对应一个折扣规则,例如购买了两本卷1,一本卷2,则可以享受5%的折扣,另外一本卷一则不享受优惠。   设计算法能够计算出读者购买一批书的最低价格。

    2.设计思想

      通过题目的分析和对情况进行推理,可得出以下的规律:以五本书为一组,如果买的数量除以5之后的余数为0/1/2/4,则花的钱数最少就是能够买一套五本的,就全都买一套,剩余不能凑齐一套的,就尽可能按照一套去买;如果余数为3,则花的钱数最少就是两套买4+4,其余的都买一套五本。

      首先输入要买的书的数量,然后求出除以5的余数,之后得到有几个一套五本。之后就进行分情况讨论即可。

    3.源代码

     1 package text;
     2 
     3 import java.util.*;
     4 
     5 public class MinMoney
     6 {
     7     public static void main(String args[])
     8     {
     9         int number = 0;
    10         double price = 0;
    11         System.out.println("请输入要买书的数量:");
    12         @SuppressWarnings("resource")
    13         Scanner in = new Scanner(System.in);
    14         number = in.nextInt();
    15         
    16         int i = 0 , times = 0;
    17         i = number % 5;
    18         times = (number - i) /5;
    19         
    20         if(i == 0)
    21         {
    22             price = times * 5 * 8 * 0.75;
    23         }
    24         else if(i == 1)
    25         {
    26             price = times * 5 * 8 * 0.75 + 8;
    27         }
    28         else if(i == 2)
    29         {
    30             price = times * 5 * 8 * 0.75 + 2 * 8 * 0.95;
    31         }
    32         else if(i == 3)
    33         {
    34             if(times == 0)
    35             {
    36                 price = 3 * 8 * 0.9;
    37             }
    38             else
    39             {
    40                 price = (times - 1) * 5 * 8 * 0.75 + 4 * 8 * 0.8 * 2;
    41             }
    42         }
    43         else if(i == 4)
    44         {
    45             price = times * 5 * 8 * 0.75 + 4 * 8 * 0.8;
    46         }
    47         
    48         System.out.println("购买该批图书的最低价格为:" + price + "。");
    49     }
    50 }

    4.结果截图

    5.个人总结

      这类题目的关键是找到题目的规律。找到相对应的规律,题目也就迎刃而解。

  • 相关阅读:
    周末之个人杂想(十三)
    PowerTip of the DaySorting Multiple Properties
    PowerTip of the DayCreate Remoting Solutions
    PowerTip of the DayAdd Help to Your Functions
    PowerTip of the DayAcessing Function Parameters by Type
    PowerTip of the DayReplace Text in Files
    PowerTip of the DayAdding Extra Information
    PowerTip of the DayPrinting Results
    Win7下IIS 7.5配置SSAS(2008)远程访问
    PowerTip of the DayOpening Current Folder in Explorer
  • 原文地址:https://www.cnblogs.com/Daddy/p/5543195.html
Copyright © 2011-2022 走看看