• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 203
  • Last Modified:

arithmetic operation returns zero

I have the following code:

int value1=0;
int value2=0;
int percent=0;

...

value1=3340;
value2=8028;
percent=((value1/value2)*100);

for some reason the above returns 0

what am I doing wrong?
0
YZlat
Asked:
YZlat
  • 2
  • 2
1 Solution
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
you are dividing integers, and 3340 / 8028 will return a value like 0.416 which will be rounded down to 0 BEFORE being multiplied by 100

solution 1:
percent=((100 * value1)/value2);

disadvantage: if value1 * 100 would be larger than the capacity of integer, you will get an overflow error

solution 2:
percent=(  ((float)(value1/value2)) *100);
0
 
YZlatAuthor Commented:
angel, solution2 gave me compile error:

Cannot implicitly convert type 'float' to 'int'
0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
indeed:
percent= (int)(  ((float)(value1/value2)) *100);
0
 
YZlatAuthor Commented:
angel, this gives me 0
0

Featured Post

Learn to develop an Android App

Want to increase your earning potential in 2018? Pad your resume with app building experience. Learn how with this hands-on course.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now