本文介绍了为什么在这个Java程序中,双引号在字符串输出中有太多的小数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在解决Java书籍艺术与科学的一个练习中,我不得不编写一个程序,将公斤转换成相当于磅和盎司的数值。
我写了程序,但是当我尝试转换1kg时,程序给我的结果是:
1 kg = 2磅和3.200000000000006盎司





任何人都知道为什么会这样发生,如何解决?谢谢!



以下是代码:

  / * 
*文件:KgsLibras.java
*以磅和盎司为单位转换公斤的程序。
* /

import acm.program。*;

public class KgsLibras extends ConsoleProgram {
public void run(){
println(该程序将以磅和盎司转换公斤);
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;
}


解决方案

这只是一个后果浮点工作 - 在这里仅仅是在这里的数以千计的其他参考。简短的版本是,并不是所有的数字都可以使用浮点数来精确表示,这会导致像你看到的那样的怪物。 应该教你所有你应该了解的浮动点。



同时,您可以使用格式获取类似printf的格式化选项:

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

或者如果您必须使用该特定的println方法,请使用String的格式:

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


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) );

这篇关于为什么在这个Java程序中,双引号在字符串输出中有太多的小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 13:22