java中十进制值的分离

ee7vknir  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(278)

所以我建立了一个程序,在那里我拿不同的硬币,把价值打印成美元和美分。因为我需要每个数字都是一个整数,所以我做了一些编码。我的问题是,在某些情况下,当运行程序时,我的美分值出现错误。其他都是对的。我假设这与转换为整数有关,当给定某个用户输入时,它会导致整数不舍入。例如,当我输入10个25美分、3个10美分、6个5美分和2个1美分时,它的结尾是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.");
    }
eqoofvh9

eqoofvh91#

很好的一天,
正确的方法是使用math.round()方法:

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

我会用同样的方法计算你的美元价值。您可能会阅读更多关于ieee754计算的内容,这里有一个很好的解释,说明了在引擎盖下发生了什么-是否有任何ieee754标准实现的java浮点原语?

rqcrx0a6

rqcrx0a62#

不要使用 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.");

这比转换要简单得多,而且算法总是精确的。

相关问题