這是小白第一次寫JAVA 只是練習 寫好玩的 若有不對敬請見諒
//原文 https://tw.knowledge.yahoo.com/question/question?qid=1515052903970
/*
問題描述 :
將一堆錢分成兩份,使這兩份錢的差額為最小。台幣可能的面額為 1000 、 500 、 100 、 50 、 10 、 5 、 1 。注意 : 原本的一堆錢是由 ” 最大的面額 ” 所組成。
輸入說明 :
輸入原本一堆錢的金額,小於一百萬。
輸出說明 :
第一行輸出金額較高一份的組成,依序輸出各項面額的數量,面額順序為 [1000, 500, 100, 50, 10, 5, 1] 。
第二行輸出金額較少一份的組成,依序輸出各項面額的數量,面額順序為 [1000, 500, 100, 50, 10, 5, 1] 。
第三行輸出兩份金額的差額,最後必須有換行字元。
範例 :
輸入範例
925
輸出範例
0 1 0 0 0 0 0
0 0 4 0 2 1 0
75
*/
import java.util.Scanner; //引用輸入變數的單元
public class 練習
{
public static void main(String args[])
{
int n=0;
int a=0;
int b=0;
int i=0;
String a1=""; // String S一定要大寫
String a2="";
int a3=0;
final int MY_ARRAY[]={1000,500,100,50,10,5,1}; //常數陣列
System.out.println("請輸入數字:"); //單純印文字
Scanner key =new Scanner(System.in); //抓剛剛輸入的數字
n=key.nextInt(); //丟入n //題目為925
for (i = 0; i <= 6; i++) { //跑一圈陣列
if (n/MY_ARRAY[i]>=1) { //如果取到第一個有幣值的數字
//System.out.println(n);
//System.out.println(MY_ARRAY[i]);
//System.out.println(n/MY_ARRAY[i]);
a=MY_ARRAY[i]; //500
b=n-a; //425
a3=a-b; //75
break; //成功取得a b 就跳出迴圈
}
}
for (i = 0; i <= 6; i++) { //跑一圈陣列
a1=a1+a/MY_ARRAY[i]+" "; //字串累加 把每次的相除的商丟進去
if (a/MY_ARRAY[i] >=1){ //如果相除>1 則
a=a-a/MY_ARRAY[i]*MY_ARRAY[i]; //變數扣掉剛剛已經用掉的數字
}
a2=a2+b/MY_ARRAY[i]+" "; //第二個變數 相同做法
if (b/MY_ARRAY[i] >=1){
b=b-b/MY_ARRAY[i]*MY_ARRAY[i];
}
}
System.out.println(a1);
System.out.println(a2);
System.out.println(a3);
}
}
然後附上 高手的解答
import java.util.Scanner;
public class a0529 {
@SuppressWarnings("resource")
public static void main(String args[]) {
try {
int money = new Scanner(System.in).nextInt(), i = 0, max1 = 0, min1 = 0;
int[] arr1 = { 1000, 500, 100, 50, 10, 5, 1 };
int[] arr = new int[arr1.length];
int[] max = new int[arr1.length];
int[] min = new int[arr1.length];
// 判斷使用者輸入的金額是否超過100萬
if (money >= 1000000) {
System.out.println("輸入金額大於100萬,程式結束。");
System.exit(0);
}
// 金額分類
for (i = 0; i < arr1.length; i++) {
arr[i] = money / arr1[i];
money %= arr1[i];
// System.out.print(arr[i] + " ");
}
for (i = 0; i < arr1.length; i++) {
if (arr[i] != 0 && max1 == 0) {
max[i] = arr[i];
max1 = arr[i] * arr1[i];
} else {
min[i] = arr[i];
min1 += (arr[i] * arr1[i]);
}
}
for (i = 0; i < arr1.length; i++)
System.out.print(max[i] + " ");
System.out.println();
for (i = 0; i < arr1.length; i++)
System.out.print(min[i] + " ");
System.out.println("\n" + (max1 - min1));
} catch (Exception e) {
System.out.println("輸入非法字元,程式結束。");
System.exit(0);
}
}
}