简体   繁体   English

在 Java 中不断收到“可能的从 double 到 int 的有损转换”错误

[英]Keep getting "possible lossy conversion from double to int" error in Java

public static int calcCarbonFootprint ( double[] person ) {

    double kgCO2;
    double metricTons;
    kgCO2 = (double)(calcTransit(person[3]));
    kgCO2 += (double)calcAutoOwnership(person[2]);
    kgCO2 += (double)calcAutoUsage(person[0],person[1]);
    metricTons = kgCO2/KGS_PER_METRIC_TON;

    return (int)metricTons;
}

This is the function I'm trying to add, but I keep getting these errors:这是我试图添加的功能,但我不断收到这些错误:

./CarbonCalculator.java:142: error: incompatible types: possible lossy conversion from double to int
    kgCO2 = (double)(calcTransit(person[3]));
                                       ^
./CarbonCalculator.java:143: error: incompatible types: possible lossy conversion from double to int
    kgCO2 += (double)calcAutoOwnership(person[2]);
                                             ^
./CarbonCalculator.java:144: error: incompatible types: possible lossy conversion from double to int
    kgCO2 += (double)calcAutoUsage(person[0],person[1]);
                                                   ^

I've tried many different approaches, but all end up in the same error.我尝试了许多不同的方法,但都以相同的错误告终。 Could I get some direction?我可以得到一些指导吗?

The error is caused by attempting to pass a double number, which has 64-bits, to an int argument, that has 32 bits.该错误是由于试图将一个 64 位的double数传递给一个 32 位的int参数引起的。

You can change the parameters of your calc* methods to accept double instead of int .您可以更改calc*方法的参数以接受double而不是int This way the calculation will be as precise as possible.这样计算将尽可能精确。

... or you can cast person[n] to int . ...或者您可以将person[n]int Some numerical data from the double type number will disappear, along with the accuracy of the calculation methods.一些来自double型数的数值数据会随着计算方法的准确性而消失。

Example code: https://ideone.com/ghgRo9示例代码: https : //ideone.com/ghgRo9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM