0

I am trying to compute a ratio between two integers, likes and dislikes. It seems to be returning 0 instead of the number I should be getting in my calculator. What am I doing wrong?

int likes = 200;
int dislikes = 100;
float ratio = (likes / 2000) * ((likes / likes) + dislikes) * 100;
i_am_jorf
  • 53,608
  • 15
  • 131
  • 222

2 Answers2

2

Integers can't represent fractions, that's what makes them integers. Doing division with integers discards the remainder, thus if you try to divide a smaller integer by a larger integer, you get 0. You're on the right track with attempting to convert them to floats, but your current implementation performs the math on the integer values before doing the conversion. You need to convert likes and dislikes to float values before you do the calculation.

Andrew Knoll
  • 211
  • 2
  • 7
0

change:

int likes = 200;
int dislikes = 100;
float ratio = (likes / 2000) * ((likes / likes) + dislikes) * 100;

to:

float likes = 200;
float dislikes = 100;
float ratio = (likes / 2000) * ((likes / likes) + dislikes) * 100;

or cast it before doing the division like this

int likes = 200;
int dislikes = 100;
float ratio = ((float)likes / 2000) * (((float)likes / likes) + dislikes) * 100;

updated: with fixed typo as pointed out in comments

Steve
  • 1,371
  • 9
  • 13