简体   繁体   中英

c++ type cast an arithmetic operation

 #include <iostream>

 int main()
 {
     long long w_popn;
     long long us_popn;
     std::cout << "Enter the world's population: ";
     std::cin >> w_popn;
     std::cout << "Enter the population of the US: ";
     std::cin >> us_popn;
     std::cout << "The population of the US is " << float (us_popn/w_popn) << "% of the world population" << std::endl;
return 0;
}

I am currently doing some exercise questions from c++ primer plus, and I am stuck at the very last print statement in my code. Particularly the part where I type float (us_popn/w_popn) . Is there a quick and dirty way of turning the results into a floating number in the cout statement without having to manually store the results in a float variable? I ask this because it seems that putting a typecast of float in front of the integer division in a cout statement doesn't seem to affect it and I end up getting 0 as a result of truncation.

您必须在除法之前强制转换操作数,否则将强制转换结果:

static_cast<float>(us_popn)/static_cast<float>(w_popn)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM