如何在Java中将1除以25(1/25)并获得结果.04 [英] How to divide 1 by 25(1/25) and get result .04 in java

查看:53
本文介绍了如何在Java中将1除以25(1/25)并获得结果.04的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果使用普通BODMAS操作执行,则返回 0 .

It returns 0 if performed with plain BODMAS operation.

我有这样的东西:

int mbUsed=1;

int mbTotal=25;

int percent=(mbUsed/mbTotal)*100;

推荐答案

Java 中的 int 数据类型包含整个值.您应该将值存储在 double float 数据类型中,因为它们可以包含小数点.

The int data type in Java contains whole values. You should instead store your values in the double or float data types, as they can contain decimal points.

在这里您可以看到一个示例:

Here you can see an example:

public static void main(String[] args) {

    int iVal1 = 1;
    int iVal2 = 25;
    int iVal3 = iVal1 / iVal2;

    System.out.println("Integer storage, int variables: " + iVal3);

    double dVal1 = iVal1 / iVal2;

    System.out.println("Double storage, int variables: " + dVal1);

    double dVal2 = (double) iVal1 / (double) iVal2;

    System.out.println("Double storage, double variables: " + dVal2);
}

哪个输出:

Integer storage, int variables: 0
Double storage, int variables: 0.0
Double storage, double variables: 0.04

请注意,您要除法的值还必须至少具有 double 个精度.在我的示例中,我只是简单地将其类型转换为 double (看到它们是整数,就没有区别),但是您也可以将它们存储在 double 数据类型中也一样

Notice how the values you are dividing also have to have at least double precision. In my example I simply type cast them to a double (seeing as they are whole numbers, it will make no difference), but you could also store them in double data types as well.

这篇关于如何在Java中将1除以25(1/25)并获得结果.04的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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