Beginner C++ Programmer Not Getting Decimal Answers

• 01-21-2012
Beginner C++ Programmer Not Getting Decimal Answers
Hey I am starting to teach myself C++ for a school project and I have just started going through the book C++ Primer Plus and I am on Chapter 3 which is mostly talking about different ways to store variables like as a int or float. I am doing the problems they have at the end of the chapter. The one I am currently on asks to find the percent of the US population out of the Worlds population using long long to store the information. Here is my code.
Code:

```#include <iostream> int main() {     using namespace std;     long long w_pop, us_pop;     long long percent;     cout<<"Enter current world's population: ";     cin>> w_pop;     cout<<endl<<"Enter current US population: ";     cin>> us_pop;     percent = (us_pop / w_pop) * 100;     cout<<endl<<"The currecnt US population is " << percent;     cout<<" percent of the world's population.";     return 0; }```
When I run the program it works for when the answer equal 1, like when I type in 5 for the worlds population and 5 for the US population, but I am not able to get it to display any numbers that actually would show a percent, like I do 5 for the world's and a 1 for the US population it will display a 0. I have looked in the book but I did not see anything that might fix it that I have learned so far. Is this caused by how the computer treats long long? Could someone explain what is causing me not to get a decimal answer? Thank you
• 01-21-2012
jimblumberg
You are using integer math, there are no fractions. You should probably be using floating point numbers, I suggest double.

Jim
• 01-21-2012
Elysia
The problem is that you are using integer math. When all operands are integers, the resulting number will have its decimals chopped off, so anything x = [0, 1) will become 0.
To fix it, at least one operand must be a float or double. You can change the type of your variables, or cast one of them to float or double, like static_cast<float>(us_pop).

Also, consider moving variable declaration closer to where you need them. For example, removing "long long percent" and changing to "float percent = (us_pop / w_pop) * 100;".
You probably don't need a long long for percent either, since it's likely going to be very small.
• 01-21-2012