简体   繁体   English

C ++,输出小数点后一位

[英]C++, output of one digit after the decimal

I'm new in C++ and would like to get some help. 我是C ++的新手,希望获得一些帮助。 I don't understand why I'm getting an output of only one digit after the decimal on the sum below. 我不明白为什么我在下面的总和的小数点后只能得到一位数字的输出。 I have tried to solve this with no success. 我试图解决此问题,但没有成功。

int main()
{
    double alt, t; 
    t = 4.5;
    // function for calculating the altitude over time.
    alt = (-0.12)*pow(t, 4) +(12.0)*pow(t, 3) -(380.0)*pow(t, 2) +(4100.0)*t +220.0;
    cout << alt << endl;
    return 0;
}

The default behaviour of cout is to print six significant digits of floating points. cout的默认行为是打印六个有效数字的浮点数。 You can change that with: 您可以使用以下方法进行更改:

cout.precision(10);
cout << alt << endl;

which gives the output: 它给出了输出:

12019.2925

which seems to be the correct solution. 这似乎是正确的解决方案。

You should not try to set the precision to anything higher than roughly 15, because that is about the precision limit of the double type (typically). 您不应尝试将精度设置为大约高于15的任何值,因为这大约是double类型的精度极限(通常)。 You can use the numeric_limits<double>::digits10 from <limits> to make sure what precision you actually have. 您可以使用<limits>numeric_limits<double>::digits10来确保实际具有的精度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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