为什么此输出为 0%

Why this output is 0%?

本文关键字:输出 为什么      更新时间:2023-10-16

该程序将计算比率。正确的输出应该是 4.50492%,但我的输出是 0%。我怀疑这是尺寸问题。但是,双精度的大小为 8 个字节,因此类型长 long 是。我的程序有什么问题?谢谢。

#include <iostream>
int main()
{
    using namespace std;
    //cout << "Enter the world's population: ";
    long long world = 6898758899;
    //cin >> world;
    //cout << "Enter the population of US: ";
    long long us = 310783781;
    //cin >> us;
    double ratio = us/world * 100;
    char percentage = '%';
    cout << "The population of the US is " << ratio << percentage << " of the world population." << endl;
    return 0;
}

因为"us"和"world"类型很长。所以"我们/世界"很长。(多头)0.0450492 == 0。

正确的拼写是

double ratio = (double)us/(double)world * 100.0;