java - 如何让除法运算符向下舍入双倍值?

标签 java

(这里完全是新手)。 我有一张额外的表格,其中包含要完成的简单练习。其中一个练习说编写一个程序,用户可以在其中输入随机金额,该程序会告诉用户需要多少欧元、50 美分、20 美分、10 美分、5 美分、2 美分和 1 美分来弥补输入的金额。 我尝试使用模数来获得所需的美分数量,

我的问题是如何让我的程序计算所需的 CENTS 数量? 每次我使用除法运算符来计算剩余金额所需的 50 美分(例如 0.60)时,它会将双倍舍入,得到 2 作为输出。

Scanner keyboard = new Scanner(System.in);

System.out.print("Input money recieved: ");
double recieve = keyboard.nextDouble();

double cents = recieve * 100;

int centsTotal = (int)cents;

System.out.print("Cents in total " + centsTotal);

int notes = centsTotal / 100;

System.out.print("\nEuros: " + notes);

double remain = recieve % notes;

System.out.printf("\nRemain: %.2f",remain);

double remain2 = remain / 0.5;

System.out.println("\nTest: ",remain2);

我的输出是:

Input money recieved: 45,78
    Cents in total 4578
    Euros: 45
    Remain: 0,78
    Test: 1.5600000000000023

最佳答案

您可以像这样使用 Math.round() 函数作弊:

double roundOff = Math.round(valueToRound * 100.0) / 100.0;

这确保您将值保持为 double 值,这样您就可以在必要时对其进行进一步的操作。

关于java - 如何让除法运算符向下舍入双倍值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39691198/

相关文章:

java - 无法将基于 Thymeleaf 的 UI 表单中的值绑定(bind)到 Spring Boot 中的 Controller

java - 在系统上运行 jar 文件时出错

java - 使用JAVA播放媒体文件

java - 如何使用 Java 获取 macOS 上的时区信息?

Java Swing - 全局更改面板以具有粉红色背景

java - 当我的 Android 应用程序在 Android 设备/模拟器上运行时,Jsoup 无法工作

Java错误: "incompatible types: int cannot be converted to Player

java - 如何将 Firebase 数据转换为 Java 对象?

java - 在javafx中更新canvas

java - org.bouncycaSTLe.asn1.DLSequence 无法转换为 org.bouncycaSTLe.asn1.ASN1Integer