gpt4 book ai didi

java - 获取不同整数的数字(Java)

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:44:39 25 4
gpt4 key购买 nike

这就是问题:考虑一个货币系统,其中有七种面额的纸币,即 Rs 1、Rs 2、Rs。 5,卢比。 10 卢比50 卢比100. 如果总和为 Rs。通过键盘输入 N,编写一个程序来计算将组合为 Rs 的最小音符数。 N.

这是我的代码。程序好像陷入死循环了

public class ReachNwithCurrencyNotes {

public static void main(String[] args) {

int n,temp = 0, a = 1, b = 2, c = 5, d = 10, e = 50, f = 100, sum = 0, countA = 0, countB = 0, countC = 0, countD = 0, countE = 0, countF = 0;

Scanner input = new Scanner (System.in);

System.out.println("Please enter N");

n = input.nextInt();

temp = n;

do {

if (temp-f>=100) {
sum = sum + f;
countF++;
temp = temp - f;
}
else if (temp-e>=50) {
sum = sum + e;
countE++;
temp = temp - e;
}
else if (temp-d>=10) {
sum = sum + d;
countD++;
temp = temp - d;
}
else if (temp-c>=5){
sum = sum + c;
countC++;
temp = temp - c;
}
else if (temp-b>=2){
sum = sum + b;
countB++;
temp = temp - b;
}
else if (temp-a>=1){
sum = sum + a;
countA++;
temp = temp - a;
}
} while (sum<n);
System.out.println("N completed with\n" + countA + "\n" + countB + "\n" + countC + "\n" + countD + "\n" + countE + "\n" + countF);
}
}

最佳答案

您的所有条件检查支付 a, b, ... 是否会留下严格正数 (>= 1)。所以你永远不会支付最后需要的账单,无论它是什么,你的总和永远不会达到 n,因此无限循环。

例如,如果您可以通过支付 5 达到 0,那么您应该这样做。

关于java - 获取不同整数的数字(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28662987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com