【问题标题】:Separating decimal value in Java在Java中分隔十进制值
【发布时间】:2020-09-07 01:19:32
【问题描述】:

所以我正在构建一个程序,在该程序中,我取出不同的硬币并将其价值打印成美元和美分。因为我需要每个都是整数,所以我做了一些编码来做到这一点。我的问题是,在某些情况下,运行程序时,我的美分值出现错误。其他一切都是正确的。我假设这与转换为整数有关,并且在给出某些用户输入时导致它不舍入。例如,当我输入 10 个 25 美分、3 个硬币、6 个镍币和 2 个便士时,最后得到 11 美分。我无法弄清楚这里的错误。

我的完整代码如下。谁能告诉我我做错了什么?

    public static void main (String[]args){

    Scanner sc=new Scanner(System.in);
    System.out.print("Enter the number of quarters: ");
    double qs=sc.nextDouble();
    System.out.print("Enter the number of dimes: ");
    double ds=sc.nextDouble();
    System.out.print("Enter the number of nickels: ");
    double ns=sc.nextDouble();
    System.out.print("Enter the number of pennies: ");
    double ps=sc.nextDouble();
    System.out.print("\n");

    double qV=0.25;
    double dV=0.10;
    double nV=0.05;
    double pV=0.01;
    double tQ=qs*qV, tD=ds*dV, tN=ns*nV, tP=ps*pV;
    double totalV=tQ+tD+tN+tP;
    int dollars=(int)totalV;
    double cent=(totalV-dollars)*100;
    int cents=(int)cent;
    
    int tqs=(int)qs;
    int tds=(int)ds;
    int tns=(int)ns;
    int tps=(int)ps;

    System.out.println("You entered "+tqs+" quarters.");
    System.out.println("You entered "+tds+" dimes.");
    System.out.println("You entered "+tns+" nickels.");
    System.out.println("You entered "+tps+" pennies.");
    System.out.print("\n");

    System.out.println("Your total is "+dollars+" dollars and "+cents+" cents.");
    }

【问题讨论】:

  • 与其处理浮点数,为什么不将实际值保留为美分?

标签: java decimal


【解决方案1】:

早安,

得到你想要的东西的正确方法是使用 Math.round() 方法:

int cents= (int) Math.round(cent);

我会对您的美元价值采用相同的方法。您可以阅读有关 IEEE 754 计算的更多信息,这里有一个很好的解释,说明引擎盖下发生了什么 - Is there any IEEE 754 standard implementations for Java floating point primitives?

【讨论】:

    【解决方案2】:

    根本不要使用double。

    硬币的数量总是整数。使用int 表示整数。

    如果以美分计算总数,金额可以是整数。使用int。

    System.out.print("Enter the number of quarters: ");
    int qs=sc.nextInt();
     … etc …
    
    int total = 25*qs + 10*ds + 5*ns + ps;
    

    现在,美元数是美分总数除以 100,美分数是总数除以 100 的余数。

    int dollars = total / 100;
    int cents = total % 100;
    System.out.println("Your total is " + dollars + " dollars and "
                       + cents + " cents.");
    

    这比必须进行转换要简单得多,而且算法总是准确的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-02
      • 1970-01-01
      • 2019-07-28
      • 2023-01-16
      • 2021-10-02
      • 2012-07-08
      • 1970-01-01
      相关资源
      最近更新 更多