当前位置:C++技术网 > 精选软件 > C++ Primer Plus 6th 3.7 编程练习题 第5题 计算人口比例

C++ Primer Plus 6th 3.7 编程练习题 第5题 计算人口比例

更新时间:2019-02-22 11:23:15浏览次数:1+次

C++ Primer Plus编程练习题3.7 第5题  计算人口比例

题目:
5.编写一个程序,要求用户输入全球当前的人口和美国当前的人口(或其他国家的人口)。将这些信息存储在long long 变量中,并让程序显示美国(或其他国家)的人口占全球人口的百分比。该程序的输出应与下面类似:
Enter the world's population: 6898758899
Enter the population of th US:310783781
The population of the US is 4.50492% of the world population.

答案:书上无答案。

C++技术网辅导详解解答:
     本题代码如下:

#include <iostream>
using namespace std;
int main()
{
    double world,us;
    cout << "Enter the world's population: ";
    cin >> world;
    cout << "Enter the population of th US: ";
    cin >> us;
    double rate = 100* us / world;
    cout << "The population of the US is "<< rate <<"% of the world population.";
    return 0;
}

    本题是一个百分比计算的测试。因为结果是有小数点的,我们需要使用浮点数来存储两个数值。这样在相除之后得到小数,如果用整数存储,直接相除得到的是整数的结果。那样就和预期不一致了。整体上还是很简单的一个程序,只是应用的比较真实,一是吸引兴趣,二是应用一下百分比计算和显示,拓宽思路和视野。