Beginner C++ Programmer Not Getting Decimal Answers

This is a discussion on Beginner C++ Programmer Not Getting Decimal Answers within the C++ Programming forums, part of the General Programming Boards category; Hey I am starting to teach myself C++ for a school project and I have just started going through the ...

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.

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

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.