Solved

arithmetic operation returns zero

Posted on 2006-11-27
4
194 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Salesforce Made Easy to Use

On-screen guidance at the moment of need enables you & your employees to focus on the core, you can now boost your adoption rates swiftly and simply with one easy tool.

Question has a verified solution.

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

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
Michael from AdRem Software explains how to view the most utilized and worst performing nodes in your network, by accessing the Top Charts view in NetCrunch network monitor (https://www.adremsoft.com/). Top Charts is a view in which you can set seve…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…

630 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