java输出两个双引字符,为什么在这个Java程序中,双引号在字符串输出中有太多的小数?...

In a solution to an exercise in the Book Art and Science of Java I had to write a program that converts Kilograms into the corresponding values in Pounds and Ounces.

I wrote the program but when I try to convert say 1kg, the result the program gives me is:

1 kg = 2 pounds and 3.200000000000006 ounces

Now my constants are 2.2 pounds per kg and 16 ounces per pound so 3.2 ounces is correct. But not with so many 0's and that 6 at the end freaks me out.

Anyone know why this happens and how it can be solved? Thank you!

Here's the code:

/*

* File: KgsLibras.java

* Program that converts kilograms in pounds and ounces.

*/

import acm.program.*;

public class KgsLibras extends ConsoleProgram {

public void run () {

println ("This program will convert kilograms in pounds and ounces");

double kgs = readDouble ("Insert kgs value: ");

double libras = kgs * LIBRAS_POR_KG;

double oncas = (libras - (int)libras) * ONCAS_POR_LIBRA;

println ((int)libras + " libras" + " e " + oncas + " Onças.");

}

private static final double LIBRAS_POR_KG = 2.2;

private static final int ONCAS_POR_LIBRA = 16;

}

解决方案

That's just a consequence of how floating point works - literally thousands of other references to these issues here on SO alone. The short version is that not all numbers can be represented exactly using floating point numbers, which leads to oddities like the one you're seeing. This document should teach you all you should know about floating point.

In the mean time you can use format to get printf-like formatting options:

System.out.format ("%.0f libras e %.2f Onças.\n",libras,oncas);

or if you have to use that specific println method, use String's format:

println(String.format ("%.0f libras e %.2f Onças.",libras,oncas) );

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值