How do I simply reduce a number by a ceratin percent in C++.

I want to reduce a number by a certain percentage so I have the following calculation in C++:

int originalNumber = 100000;
double reduceBy = (100 - m_percent) / 100;
int reducedNumber = (int)(originalNumber * reduceBy );

Open in new window


If m_percent is e.g. 10 then reduceBy will be 0.000000000000.

How do I simply reduce a number by a ceratin percent in C++.
Wanting2LearnManAsked:
Who is Participating?
 
jkrConnect With a Mentor Commented:
You need to ensure that arithmetic operations are carried out as floating point operations, e.g.
int originalNumber = 100000;
double reduceBy = (100.0 - (double)m_percent) / 100.0;
int reducedNumber = (int)((double)originalNumber * reduceBy );

Open in new window

0
 
farzanjCommented:
Please give some more example of what you mean reduce by.

My interpretation would be

reducedNumber = (100-m_percent) * originalNumber;
0
 
Wanting2LearnManAuthor Commented:
Thanks jkr, it now works.

Is the above code fine? or is there a 'better' way to do this calcluation???
0
 
jkrCommented:
The code seems OK. The problem was just that if integers are in the game, you can easily truncate values to zero by a single multiplication, thus the caveat about floating point operations.
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.

All Courses

From novice to tech pro — start learning today.