正确使用std :: cout.precision() - 不打印结尾零 [英] Correct use of std::cout.precision() - not printing trailing zeros

查看:359
本文介绍了正确使用std :: cout.precision() - 不打印结尾零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
}

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

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

推荐答案

#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;
}

您需要传递 std :: fixed 操作符 cout 以显示尾随零。

You need to pass std::fixed manipulator to cout in order to show trailing zeroes.

这篇关于正确使用std :: cout.precision() - 不打印结尾零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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