C++ 正确使用 std::cout.precision() - 不打印尾随零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17341870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:06:25  来源:igfitidea点击:

Correct use of std::cout.precision() - not printing trailing zeros

c++floating-point-precision

提问by mahmood

I see many questions about the precision number for floating point numbers but specifically I want to know why this code

我看到很多关于浮点数精度数的问题,但特别是我想知道为什么这个代码

#include <iostream>
#include <stdlib.h>
int main()
{
  int a = 5;
  int b = 10;
  std::cout.precision(4);
  std::cout << (float)a/(float)b << "\n";
  return 0;
}

shows 0.5? I expect to see 0.5000. Is it because of the original integer data types?

显示0.5? 我期待看到0.5000。是因为原始整数数据类型吗?

回答by Nemanja Boric

#include <iostream>
#include <stdlib.h>
#include <iomanip>
int main()
{
  int a = 5;
  int b = 10;
  std::cout << std::fixed;
  std::cout << std::setprecision(4);
  std::cout << (float)a/(float)b << "\n";
  return 0;
}

You need to pass std::fixedmanipulator to coutin order to show trailing zeroes.

您需要将std::fixed操纵器传递给以cout显示尾随零。

回答by stardust

std::cout.precision(4);tells the maximum number of digits to usenot the minimum. that means, for example, if you use

std::cout.precision(4);告诉使用的最大位数而不是最小位数。这意味着,例如,如果您使用

precision 4 on 1.23456 you get 1.235  
precision 5 on 1.23456 you get 1.2346

If you want to get ndigits at all times you would have to use std::fixed.

如果您想n始终获得数字,则必须使用std::fixed.

回答by Nikos C.

The behavior is correct. The argument specifies the maximum meaningful amount of digits to use. It is not a minimum. If only zeroes follow, they are not printed because zeroes at the end of a decimal part are not meaningful. If you want the zeroes printed, then you need to set appropriate flags:

行为是正确的。该参数指定要使用的最大有意义的数字量。这不是最低限度。如果后面只有零,则不会打印它们,因为小数部分末尾的零没有意义。如果要打印零,则需要设置适当的标志:

std::cout.setf(std::ios::fixed, std::ios::floatfield);

This sets the notation to "fixed", which prints all digits.

这将符号设置为“固定”,打印所有数字。