Java程序错误:可能会丢失精度 [英] Java program error: possible loss of precision

查看:287
本文介绍了Java程序错误:可能会丢失精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚为什么我在Java程序中出现这种精度错误的错误。

I am trying to figure out why I am getting this loss of precision error in my Java program.

这是错误:

error: possible loss of precision
         int digit = num/Math.pow(10,i-1)%10;
                                         ^
  required: int
  found:    double
1 error

这是for循环中的代码片段

This is the code clip inside a for loop

for(int i = 1; i<=String.valueOf(num).length(); i++)
{
    int digit = num/Math.pow(10,i-1)%10;
    //etc
}

我想将数字保持为整数变量,我试图在循环外声明数字,我也尝试将其转换为一个不起作用的整数。我确实尝试过这样做:

I want to keep digit as an integer variable, and I tried to declare digit outside the loop, and I also tried casting it into an integer which didn't work. I did try doing it as:

digit += num/Math.pow(10,i-1)%10; //with digit declare outside of loop

神奇地工作,但我不想增加它,而我希望它包含我以后可以使用的数字。这里有什么我想念的吗?请解释。

which worked magically, but I don't want to increment it, instead I want it to contain the digit which I can use for later. Is there something I'm missing here? Please explain.

推荐答案

我尝试按如下方式运行您的代码:

I tried to run your code as follows:

int digit = (int) (num/Math.pow(10,i-1)%10);

它按预期工作,即它遍历变量num的数字(我假设为int)。

And it worked as expected, i.e. it iterated through the digits of your variable num (which I assumed as int).

当你使用+ =运算符时,它不是因为魔法,而是因为自动类型提升。您可以在此处阅读更多相关信息: http:// docs.oracle.com/javase/specs/jls/se7/html/jls-5.html

When you use the += operator, it works not because of magic, but because of automatic type promotion. You can read more about it here: http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html

这篇关于Java程序错误:可能会丢失精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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