简体   繁体   English

以精度2打印浮点数但在C ++中没有小数(。)

[英]Printing float with precision 2 but without decimal(.) in C++

Please Consider Code snippet shown below: 请考虑以下代码段:

// setprecision example
#include <iostream>     // std::cout, std::fixed
#include <iomanip>      // std::setprecision

int main () {
  double f =3.14159;
  std::cout.precision(2);

  std::cout << f*100 << '\n';
  return 0;
}

What I want to do is print on screen 314 (ie print f without decimal with precision as 2) 我想要做的是在屏幕314上打印(即打印f没有小数,精度为2)

I want thinking of first setting precision as 2 and then multiplying with 100. 我想首先将精度设置为2,然后乘以100。

But it seems that precision is finally applied on f*100. 但似乎精确度最终应用于f * 100。 Can anyone suggest of any way to apply precision on f then to multiply the number by 100 and finally to print with precision 0? 谁能建议任何方法在f上应用精度然后将数字乘以100,最后以精度0打印?

Multiply by a 100 and print with precision 0. 乘以100,精确打印0。

int main () {
  double f =3.14159;
  std::cout.precision(0);

  std::cout << std::fixed << f*100 << '\n';
  return 0;
}

There's actually a "proper" way to do this, without having to alter the value at all. 实际上有一种“正确”的方式,而不必改变价值。 You can prepare an std::ostringstream that will do this for you by using your own std::numpunct subclass: 您可以使用自己的std::numpunct子类准备一个std::ostringstream ,它将为您执行此操作:

#include <locale>

class no_decimal_punct: public std::numpunct<char> {
protected:
    virtual char do_decimal_point() const
    { return '\0'; }
};

You can now prepare an std::ostringstream that will use the above no_decimal_punct class: 您现在可以准备一个将使用上述no_decimal_punct类的std::ostringstream

#include <sstream>
#include <iostream>

std::ostringstream strm;
strm.imbue(std::locale(strm.getloc(), new no_decimal_punct));
strm.precision(2);
std::fixed(strm);

double f = 3.14159;
strm << f;
std::cout << strm.str() << '\n';

The advantage here is that you're not changing the value of f , which could potentially print something else than intended due to FP errors. 这里的优点是你没有改变f的值,由于FP错误, f可能会打印出比预期更多的东西。

There are many ways to display 314: 显示314的方法有很多种:

#include <iostream>
using namespace std;
int main() {
  const double PI = 3.1415926;
  cout.precision(3);
  cout<<PI * 100<<endl;
}

#include <iostream>
using namespace std;
int main() {
  const double PI = 3.1415926;
  cout<<(int)(PI * 100)<<endl;
}

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

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