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

# 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
• 2
• 2
1 Solution

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

Author Commented:
angel, solution2 gave me compile error:

Cannot implicitly convert type 'float' to 'int'
0

Billing EngineerCommented:
indeed:
percent= (int)(  ((float)(value1/value2)) *100);
0

Author Commented:
angel, this gives me 0
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

## Featured Post

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