Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

why is this zero  RSS feed

 
abhishek rathur
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

public class roundoff {
public static void main(String[] args)
{
float f=(10/40)*10;
int i= Math.round(f);
System.out.println(i);
}

}

why the output of this is 0
 
Stephan van Hulst
Saloon Keeper
Posts: 7983
143
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because you're dividing an integer by another integer. 10/40 is 0 in Java. Try 10.0/40.

Why are you using float instead of double?
 
abhishek rathur
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you very much for the quick response..
 
Randall Twede
Ranch Hand
Posts: 4696
8
Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why are you using float instead of double?

i almost started a thread about this, but since it got mentioned i will bring it up here. i use int mostly and long if i have to but when it come to floating point numbers i always used double. i think most people do. why use float? but why is this? why not use long more often or float when it works?
 
Stephan van Hulst
Saloon Keeper
Posts: 7983
143
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Simple. They are the default. If you don't have a good reason to use anything else, you might as well just use the default, right? So why are they default? Probably because most RISC processors natively support 32 bit integer operations, and 64 bit floating point operations.

Using the smaller data types (byte, short and float) is usually only appropriate when you need to store data in some compact file format.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!