Beginner Java question (int, float)

int cinema,dvd,pc,total; double fractionCinema, fractionOther; fractionCinema=(cinema/total)*100; //percent cinema 

So, when I run the code to display fractionCinema, it just gives me zeros. If I change all ints to paired, then this will give me what I'm looking for. However, I use cinema, a computer, and everything else, and they should display as ints, not decimals. What should I do?

+4
source share
4 answers

When you divide two ints (e.g. 2/3), Java performs integer division and truncates the decimal part.
Therefore, 2 / 3 == 0 .

You need to force Java to do the double split, discarding either the operand to double .

For instance:

 fractionCinema = (cinema / (double)total) * 100; 
+13
source

Try this instead:

 int cinema, total; int fractionCinema; fractionCinema = cinema*100 / total; //percent cinema 

For example, if cinema/(double)total is 0.5, then fractionCinema will be 50. And no floating point operations are required; all math is done using integer arithmetic.

Adding

As stated in @ user949300, the code above is rounded to the nearest integer. To round the result β€œcorrectly”, use this:

 fractionCinema = (cinema*100 + 50) / total; //percent cinema 
+5
source

When you split two int s, Java will perform integer division, and the fractional part will be truncated.

You can explicitly specify one of the arguments to double via cinema/(double) total or implicitly use an operation such as cinema*1.0/total

+2
source

As some people have already noted, Java will automatically cut off any fractional parts when separating integers. Just change the variables from int to double.

0
source

All Articles