• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

why won't "float x = 1.0;" compile

 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I understand that

float x = 1.0; // generates a compile error

and

double x = 1.0; // compiles

But does anyone understand the reasoning behind this. Why isn't 1.0 considered to be an acceptable value for float types??

Thanks
 
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Default type of values having decimal point is double. So, 1.0 is double and not float.
 
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
The compiler takes floating point literals as Double by default. That is why it shows an error. We can specify it as a float by adding 'f'.
like float x = 1.0f; Here we tell the compiler that this is a float, so dont take as a double.
-vipin
 
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
However "float x = 1;" using an integer literal compiles OK.

javac is concerned that converting a double value to a float value will lose precision.

You would need either "float x = 1.f;" or "float x = (float)1.;
 
reply
    Bookmark Topic Watch Topic
  • New Topic