假設商店貨品價格(R) 都不大於100元(且為整數),若顧客付款(P)在100元內,現有一個程序能在每位顧客付款后給出找零錢的最佳組合(找給顧客貨幣張數最少)。 假定此商店的貨幣面值只包括:50元(N50)、10元(N10)、 5元(N5)、1元(N1) 四種。
下面為程序的代碼:
/************************************************************
Copyright (C), 1988-1999, Huawei Tech. Co., Ltd.
FileName: test.cpp
Author: Light
Version : 1.0
Date: 2018/4/17
Description:
假設商店貨品價格(R) 都不大於100元(且為整數),若顧客付款(P)在100元內,
現有一個程序能在每位顧客付款后給出找零錢的最佳組合(找給顧客貨幣張數最少)。
假定此商店的貨幣面值只包括:50元(N50)、10元(N10)、 5元(N5)、1元(N1) 四種
// 模塊描述
Version:
僅用於軟件測試,完成作業
// 版本信息
Function List: // 主要函數及其功能
1.
History:
// 歷史修改記錄
<author> <time> <version > <desc>
Light 18/4/17 1.0 建立函數
***********************************************************/
package demo;
import java.util.Scanner;
public class main {
/**
* 主函數
* @param args
*/
public static void main (String[] args) {
// TODO Auto-generated method stub
int pay = 0;//付款金額
int cost = 0;//商品花費
int change = 0;//找錢
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入顧客付款金額:");
//對輸入的內容進行檢測,是否符合規則
try
{
pay = scanner.nextInt();
if (pay > 100 || pay < 0)
{
System.out.println("請輸入正確的金額");
return;
}
}catch (Exception e)
{
System.out.println("請輸入合法數字");
return;
}
System.out.println("請輸入商店貨品價格:");
//對輸入的內容進行檢測,是否符合規則
try
{
cost = scanner.nextInt();
if (cost > 100 || cost < 0)
{
System.out.println("請輸入正確的金額");
return;
}
else if (cost > pay)
{
System.out.println("您的消費金額超出支付金額");
return;
}
}catch (Exception e)
{
System.out.println("請輸入合法數字");
return;
}
change = pay-cost;
//輸出此時的付款金額,商品價格,應找金額
System.out.println("付款金額" + pay +" 貨品價格" + cost + " 應找總金額:" + change);
//獲得結果,進行輸出
String end = giveChange(change);
System.out.println("此次消費應找金額 " + change + " 元,其中應找 " + end);
}
/**
* 以找錢規則找錢
* @param change
* @return String//返回最終的找錢結果
*/
public static String giveChange(int change)
{
String str="";
int qianshu;//應該找錢的張數
int leftmoney = change;//還剩下多少錢,初始值為change
if (leftmoney / 50 != 0)
{
qianshu = leftmoney / 50;
str = str + qianshu + "張50元 ";
leftmoney = leftmoney - qianshu * 50;
}
if (leftmoney / 10 != 0)
{
qianshu = leftmoney / 10;
str = str + qianshu + "張10元 ";
leftmoney = leftmoney - qianshu * 10;
}
if (leftmoney / 5 != 0)
{
qianshu = leftmoney / 5;
str = str + qianshu + "張5元 ";
leftmoney = leftmoney - qianshu * 5;
}
if (leftmoney / 1 != 0)
{
qianshu = leftmoney / 1;
str = str + qianshu + "張1元 ";
leftmoney = leftmoney - qianshu * 1;
}
//檢驗是否完全找完
System.out.println("剩余沒有找完的錢數為:"+leftmoney);
return str;
}
}
