Java应用程序的结果不应该是四舍五入 [英] Java rounding the results of a division when it shouldn't be

查看:122
本文介绍了Java应用程序的结果不应该是四舍五入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一些代码通过将理想屏幕的大小除以用户屏幕的大小,将图形缩放到用户屏幕的大小。 Hers是我正在做的代码片段:

So I have some code for scaling graphics to the size of a users screen by dividing the size of an 'Ideal' screen by the size of the users screen. Hers is a code snippet of what I'm doing:

public void setScaleFactor(GameContainer ui) {
    scaleFactorWidth = 2880 / ui.getWidth();
    scaleFactorHeight = 1800 / ui.getHeight();

    System.out.println("Screen measured as: "
            + Integer.toString(ui.getWidth()) + "x"
            + Integer.toString(ui.getHeight()));

    System.out.println("Scale factors are: "
            + Double.toString(scaleFactorWidth) + " "
            + Double.toString(scaleFactorHeight));

    textScale = (scaleFactorWidth + scaleFactorHeight) / 2;

    System.out.println("Text scale is: " + Double.toString(textScale));
}

现在如果我在我的电脑上运行这个(Mac Book pro,屏幕分辨率的1440x900),scaleFactorWidth设置为2.0,scaleFactorHeight设置为2.0,这是正如预期的,因为我的屏幕是目标的一半大小。但是如果在具有不同分辨率屏幕的计算机上运行此代码,那么scaleFactors似乎会被四舍五入,我在1024x600的屏幕上运行测试,scaleFactorWidth设置为2.0,scaleFactorHeight设置为3.0时应该已经是2.8125 x 3.0。

Now if i run this on my computer (Mac Book pro with a screen resolution of 1440x900) the out come is that "scaleFactorWidth" is set to 2.0 and "scaleFactorHeight" is set to 2.0, this is as expected since my screen is exactly half the size of the target. But if run this code on a computer with a different resolution screen then the scaleFactors seem to get rounded up, I ran a test on a screen with 1024x600 and the "scaleFactorWidth" was set to 2.0 "scaleFactorHeight" was set to 3.0 when it should have been 2.8125 x 3.0.

这是java中的一些舍入错误,如果是这样,我该如何解决?

IS this some sort of rounding error within java and if so how do I fix it?

编辑:感谢所有的帮助,我意识到我非常愚蠢,因为我需要做的是添加.0到2880和1800。

Thanks for all the help, I've realised I was being very stupid as all I needed to do was add .0 to 2880 and 1800.

推荐答案

在这些行中

scaleFactorWidth = 2880 / ui.getWidth();
scaleFactorHeight = 1800 / ui.getHeight();

计算本身是基于整数的(根据稍后调用的整数的ToString())。只是结果被转移到 double

The calculation itself is Integer-based (according to the later calls of Integer.toString()). Just the result is then casted to double.

使用此代码,以便实际计算使用 double values:

Use this code instead, in order to have the actual computation use double values:

scaleFactorWidth = 2880.0 / ui.getWidth();
scaleFactorHeight = 1800.0 / ui.getHeight();

scaleFactorWidth = 2880.0 / (double)ui.getWidth();
scaleFactorHeight = 1800.0 / (double)ui.getHeight();

这篇关于Java应用程序的结果不应该是四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆