Solved

arithmetic operation returns zero

Posted on 2006-11-27
4
187 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 142

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 125 total points
Comment Utility
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
Comment Utility
angel, solution2 gave me compile error:

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

Expert Comment

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

Author Comment

by:YZlat
Comment Utility
angel, this gives me 0
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Bit flags and bit flag manipulation is perhaps one of the most underrated strategies in programming, likely because most programmers developing in high-level languages rely too much on the high-level features, and forget about the low-level ones. Th…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

762 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now