Multiplying float values “possible lossy conversion from double to float”

孤街醉人 提交于 2019-12-17 21:17:29

问题


I have this problem wherein I have to convert kilometers into miles. I'm a novice programmer so bear with me.

Here's my code so far:

import java.util.Scanner;

public class problem1 {
    public static void main (String args[]) {
        float m;
        float km;

        Scanner input=new Scanner(System.in);

        System.out.print("Please enter a distance in kilometers:");
        km=input.nextFloat();
        m=km*0.621371;
        System.out.println("This is equal to: "+m);
    }
}

It gives me an error saying:

Incompatible types:possible lossy conversion from double to float.

回答1:


You are trying to set a double to a float variable

To fix, change this line

m=km*0.621371;

to

m=km*0.621371f;



回答2:


The value 0.621371 is a double literal, so the km values is promoted to double when multiplied. Storing the double product back to m would be a conversion that could lose data (double to float).

To keep the data as a float, use a float literal, with a f on the end:

m=km*0.621371f;

Normally a double for the results would be just fine, so you could also just change the datatypes of m and km to double.




回答3:


You need to define constant variable as a float, since km is read as a float.

final float KM_TO_ML = 0.621371F;
m = km * KM_TO_ML;


来源:https://stackoverflow.com/questions/28484379/multiplying-float-values-possible-lossy-conversion-from-double-to-float

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!