Need help with my double return function.
Code :
public class Rectangle{
public int num;
public int den;
public double val;
public void display(){
System.out.println(num);
System.out.println(den);
}
public double doubleValue(){
val = num / den;
return val;
}
public static void main(String[] args) {
Rectangle x = new Rectangle();
x.num = 5;
x.den = 25;
x.display();
System.out.println(x.doubleValue());
}
}
Apparently when I print out the doubleValue() function it just sends a 0.0 value and does not give the right answer which is 0.2
I cant seen to find what is wrong in my code, care to help?
Re: Need help with my double return function.
Check that your code is NOT doing integer arithmetic. For example 5/6 = 0 vs 5.0/6 = 0.833333
To force the compiler to use floating point arithmetic multiply a value by by 1.0 before dividing.
Re: Need help with my double return function.
Quote:
Originally Posted by
Norm
Check that your code is NOT doing integer arithmetic. For example 5/6 = 0 vs 5.0/6 = 0.833333
To force the compiler to use floating point arithmetic multiply a value by by 1.0 before dividing.
Thanks I tried it and it worked!
im just wondering if thats the only way to force the compiler to use floating point arithmetic?
Re: Need help with my double return function.
The compiler looks at the data types used in a computation and uses the arithmetic that matches those values.
If there are mixed data types, there are rules the compiler uses to chose which type of arithmetic to use.
Google or some search will tell you what they are. I don't know them by heart.
Re: Need help with my double return function.
Quote:
im just wondering if thats the only way to force the compiler to use floating point arithmetic?
It's not the only way - casting one of the ints in your expression to a floating point type might be safer. If a mathematician was involved in writing your compiler, she might 'optimise out' a constant multiplication by 1.0 as an identity operation (she hasn't and '* 1.0' does work, but I like to be explicit about what type I'm using). The Java Language Specification is the place to look for the definitive view, but it's not exactly light reading:
Conversions and Promotions