18

我有一个浮点数,例如 12.12123 是否有一个函数可以只显示小数点 12.12 后 2 位的数字?

这是代码:

y1 = ( c1 - (a1 * x)) / b1;
 y2 = ( c2 - a2 * x) / b2;

if (y1 == y2)
  cout << "The same";

所以如果 y1 = 1.001 和 y2 = 1.002 它们看起来不一样。

我尝试添加。cout.setf(ios::fixed, ios::floatfield); cout.precision(2);

但这似乎没有帮助。

4

7 回答 7

38
/* The C way */
#include <stdio.h>
...
float f = 12.12123f;
printf("%.2f",f);

// The C++ way
#include <iostream>
...
float f = 12.12123f;
std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
std::cout.precision(2);
std::cout << f;

// The alternative C++ way
#include <iostream>
#include <iomanip>
...
float f = 12.12123f;
std::cout << std::fixed << std::setprecision(2) << f;

在 C 中,如果没有足够的数字来打印,0 填充会自动添加到右侧。相反,在 C++ 示例中,这是禁用的;要启用此行为,您应该在流上启用固定模式std::fixed(或启用相关的流标志std::ios_base::setf())。

编辑:我记错了;如果fixed未设置,则该precision设置向流说明要显示的位数,包括小数点前的位数。因此,在这种情况下,我认为唯一的方法是使用fixed模式(示例已修复),这将产生与printf.


链接:

于 2010-10-13T11:45:29.227 回答
7

您正在寻找printf("%.2f", 12.12123);或:

#include <iostream>
#include <iomanip>

using namespace std;
cout << fixed << setprecision(2) << 12.12123;

编辑:问题变了,答案也变了。

您永远不想使用浮点直接相等,您总是在epsilon容差范围内进行比较。你epsilon的只是相当大。

替换if (y1 == y2)if (abs(y1 - y2) < 0.01)

于 2010-10-13T11:42:58.767 回答
3
double num = 1.4567;
printf("%.2f",num);

这将打印 1.46

于 2010-10-13T11:44:25.750 回答
2

You are probably asking wrong question. Try following:

double diff = fabs(y1-y2);
if(diff < 0.005)
    cout << "Almost same";
于 2010-10-13T12:13:57.507 回答
2
cout.precision(2);
cout <<f;
于 2010-10-13T11:45:05.517 回答
2
#include <iostream>
#include <iomanip>

int main ()
{
   double d = 1.242354345; 
   using namespace std;
   cout << setiosflags(ios::fixed | ios::showpoint)
        << setprecision(2)
        << d; 
}
于 2010-10-13T11:59:05.730 回答
1
cout.setf(ios::fixed, ios::floatfield);
cout.precision(2);
float al = 42.645; //sample
cout << al;
于 2010-10-13T11:47:40.363 回答