int cinema,dvd,pc,total;
double fractionCinema, fractionOther;
fractionCinema=(cinema/total)*100; //percent cinema
So when I run code to display fractionCinema, it just gives me zeros. If I change all the ints to doubles, then it gives me what Im looking for. However, I use cinema, pc, and total elsewhere and they have to be displayed as ints, not decimals. What do I do?
When you divide two ints (eg, 2 / 3
), Java performs an integer division, and truncates the decimal portion.
Therefore, 2 / 3 == 0
.
You need to force Java to perform a double
division by casting either operand to a double
.
For example:
fractionCinema = (cinema / (double)total) * 100;
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
would be 50. And no floating-point operations are required; all of the math is done using integer arithmetic.
Addendum
As pointed out by @user949300, the code above rounds down to the nearest integer. To round the result "properly", use this:
fractionCinema = (cinema*100 + 50) / total; //percent cinema
When you divide two int
s, Java will do integer division, and the fractional part will be truncated.
You can either explicitly cast one of the arguments to a double via cinema/(double) total
or implicitly using an operation such as cinema*1.0/total
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With