Solved

arithmetic operation returns zero

Posted on 2006-11-27
4
190 Views
Last Modified: 2010-04-16
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
Comment
Question by:YZlat
  • 2
  • 2
4 Comments
 
LVL 143

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 125 total points
ID: 18023009
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
 
LVL 35

Author Comment

by:YZlat
ID: 18023163
angel, solution2 gave me compile error:

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

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 18023187
indeed:
percent= (int)(  ((float)(value1/value2)) *100);
0
 
LVL 35

Author Comment

by:YZlat
ID: 18028232
angel, this gives me 0
0

Featured Post

Active Directory Webinar

We all know we need to protect and secure our privileges, but where to start? Join Experts Exchange and ManageEngine on Tuesday, April 11, 2017 10:00 AM PDT to learn how to track and secure privileged users in Active Directory.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applicationsā€¦
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that undeā€¦

827 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question