gpt4 book ai didi

Java 模数运算符无法正常工作

转载 作者:行者123 更新时间:2023-12-02 00:47:57 27 4
gpt4 key购买 nike

我正在编写一个小程序,当我输入金额时,它会给出每种硬币类别(25美分、10美分等)的最大金额。模运算符未返回正确的值。例如,当我输入金额“1.64”时,它应该返回:25 美分:6,一角硬币:1,镍币:0,便士:4。但我的问题在于便士。它一直只返回 3 便士。任何意见将不胜感激!

import java.util.Scanner;

public class Main{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter amount: ");
double amount = in.nextDouble();

int quarters = (int)(amount / 0.25);
System.out.println("Quarters: " + quarters);

amount = (amount % 0.25);

int dimes = (int)(amount / 0.1);
System.out.println("Dimes: " + dimes);

amount = (amount % 0.1);

int nickels = (int)(amount / 0.05);
System.out.println("Nickels: " + nickels);

amount = (amount % 0.05);

int pennies = (int)(amount / 0.01);
System.out.println("Pennies: " + pennies);
}
}

输入金额:1.64宿舍:6一毛钱:1镍:0便士:3

最佳答案

我建议您使用基本减法,而不是在每个步骤后通过模数重置amount。然后简单地乘以最后的剩余总数就可以得到几美分。例如,

int quarters = (int) (amount / 0.25);
System.out.println("Quarters: " + quarters);

amount -= (quarters * 0.25); // (remove quarters)

int dimes = (int) (amount / 0.1);
System.out.println("Dimes: " + dimes);

amount -= (dimes * 0.1); // (remove dimes)

int nickels = (int) (amount / 0.05);
System.out.println("Nickels: " + nickels);

amount -= (nickels * 0.05); // remove nickels, all that's left is pennies (in cents)
System.out.println("Pennies: " + Math.round(100 * amount));

关于Java 模数运算符无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57883154/

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