[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
Solved

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

Posted on 2011-10-24
Medium Priority
280 Views
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 );
``````

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++.
0
Question by:Wanting2LearnMan
• 2

LVL 86

Accepted Solution

jkr earned 1000 total points
ID: 37019132
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 );
``````
0

LVL 31

Expert Comment

ID: 37019138
Please give some more example of what you mean reduce by.

My interpretation would be

reducedNumber = (100-m_percent) * originalNumber;
0

Author Comment

ID: 37019182
Thanks jkr, it now works.

Is the above code fine? or is there a 'better' way to do this calcluation???
0

LVL 86

Expert Comment

ID: 37019193
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

## Featured Post

Question has a verified solution.

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

C++ Properties One feature missing from standard C++ that you will find in many other Object Oriented Programming languages is something called a Property (http://www.experts-exchange.com/Programming/Languages/CPP/A_3912-Object-Properties-in-C.ht…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
###### Suggested Courses
Course of the Month18 days, 14 hours left to enroll