std :: cout带有浮点数 [英] std::cout with floating number

查看:88
本文介绍了std :: cout带有浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Visual Studio 2015打印两个浮点数:

I'm using visual studio 2015 to print two floating numbers:

double d1 = 1.5;
double d2 = 123456.789;

std::cout << "value1: " << d1 << std::endl;
std::cout << "value2: " << d2 << std::endl;

std::cout << "maximum number of significant decimal digits (value1): " << -std::log10(std::nextafter(d1, std::numeric_limits<double>::max()) - d1) << std::endl;
std::cout << "maximum number of significant decimal digits (value2): " << -std::log10(std::nextafter(d2, std::numeric_limits<double>::max()) - d2) << std::endl;

这将打印以下内容:

value1: 1.5
value2: 123457
maximum number of significant decimal digits (value1): 15.6536
maximum number of significant decimal digits (value2): 10.8371

为什么打印出123457的值是123456.789?在不使用std :: setprecision()的情况下使用std :: cout时,ANSI C ++规范是否允许显示浮点数?

Why 123457 is print out for value 123456.789? Does ANSI C++ specification allow to display anything for floating numbers when std::cout is used without std::setprecision()?

推荐答案

四舍五入的发生是由于C ++标准可以通过编写看到的 std :: cout<< std :: cout.precision();

The rounding off happens because of the C++ standard which can be seen by writing std::cout<<std::cout.precision();

输出屏幕上将显示6,这表明cout语句将打印的默认有效数字位数为6.这就是为什么它将自动将浮点数四舍五入到6位数字的原因.

The output screen will show 6 which tells that the default number of significant digits which will be printed by cout statement is 6. That is why it automatically rounds off the floating number to 6 digits.

这篇关于std :: cout带有浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆