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

牧云@^-^@ 提交于 2019-11-26 17:50:49
#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::fixed manipulator to cout in order to show trailing zeroes.

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

precision 4 on 1.23456 you get 1.234  
precision 5 on 1.23456 you get 1.2345

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!