0
Can Java functions accept variables that are floats?
Why am I seeing this warning in the Java compiler? Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method sum(float, float) in the type calc is not applicable for the arguments (double, double)
4 Respuestas
+ 2
Cast the arguments before passing to the function
sum((float)arg1, (float)arg1);
But I'd recommend you use double as your function parameter types instead of float. Double is more precise than float and so Java allows float-to-double conversions but not double-to-float conversions. Because the second type u mentioned might lose some information(accuracy or some floating point digits).
I always use double and almost never use float =)
+ 2
Example:
Let's see a simple example to display float type variable.
public class FloatExample1 {
public static void main(String[] args) {
float num1=5.5f;
float num2=5f;
System.out.println("num1: "+num1);
System.out.println("num2: "+num2);
}
}
Output:
num1: 5.5
num2: 5.0
+ 1
Here look how it works with float
https://code.sololearn.com/cWP0Ia9R4w87/?ref=app
+ 1
If you pass floating point literals then FYI floating point literals are of `double` type rather than `float`.
But you can specify the literal as `float` by appending float tyoe notation e.g.
YourClass.yourMethod( 1.23f, 4.56f );