programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# why float f=1/3 is 0?

michael wang
Ranch Hand
Posts: 35
it compiles and print 0.0
why?
thanks

Nazmul Huda Sarkar
Ranch Hand
Posts: 317
here 1 and 3 both r integer..right? so an integer division 1/3 = 0 then 0 is promoted to
float...so it is 0.0
float f = 1/3
float f = (float) (1/3)
float f = (float) (0)
so f=0.0

but if it is 1.0/3 or 1/3.0 then the result would be different...'coz first both will be promoted to float and it would then be a floating point division....
am I right ?

michael wang
Ranch Hand
Posts: 35
float f=(float)(1.0/3.0);
System.out.println(f);//print 0.33333334
float d = 1/3;
System.out.println(d);//print 0.0
//float e = 1.0/3;//compile time error
//float e = 1/3.0;//compile time error
//float e = (float)1.0/3;//compile time error
}
}

Manish Hatwalne
Ranch Hand
Posts: 2596
Originally posted by michael wang:
float f=(float)(1.0/3.0);
System.out.println(f);//print 0.33333334
float d = 1/3;
System.out.println(d);//print 0.0
//float e = 1.0/3;//compile time error
//float e = 1/3.0;//compile time error
//float e = (float)1.0/3;//compile time error
}
}

1.0 as or 3.0 is a double value. Use 1.0f and 3.0f etc.
HTH,
- Manish

Jose Botella
Ranch Hand
Posts: 2120
Michael
float e = (float)1.0/3
compiles ok

michael wang
Ranch Hand
Posts: 35
Originally posted by Jose Botella:
Michael
float e = (float)1.0/3
compiles ok

sorry for that
i want to say
float e=(float)1.0/3.0

Nazmul Huda Sarkar
Ranch Hand
Posts: 317
ofcourse proper syntax must be taken care of but if u understand why float f=1/3 result 0.0 and float f=(float)1/3 result 0.33333 , then its ok.

Stefan Koeltze
Greenhorn
Posts: 14
Hi all!
3.0 by default is a double!!!
(float)1.0/3;
is the same as:
(float)1.0/(int)3; and a int will be expanded to a float ... so there is no problem.
(float)1.0/3.0;
is the same as:
(float)1.0/(double)3.0; so we hav incompatible types ... so without casting we have a compile error.
(float)(1.0/3.0);
is by default the same as:
(float)((double)1.0/(double)3.0);
...so ... no problem
Ok!?
Ciao Stefano