将非常小的数字舍入为零 (c++)

Round very small numbers to zero (c++)

有没有C++命令可以制作,

1.354322e-23

进入

0

这是我的(简单)程序

#include "stdafx.h"
#include <iostream>
#include<iomanip>

int main()
{
    float x;
    std::cin >> x;
    std::cout << x << std::endl;
    return 0;
}

当我输入像这样的值时,

2.2356e-17

它给出,

2.2356e-017

std::setprecision 也不行...

编辑: 好的,这是我的问题。 我创建了一个程序,可以给出 sin costan 值。

对于cos 90,我希望它是0而不是-4.311e-008

这是我的真实程序

#include "stdafx.h"
#include <iostream>
#include<iomanip>

float Pi()
{
  float pi = (atan(1) * 4);
  return pi;
}

int Selector()
{
  using namespace std;
  cout << "Type:\t1 for Degrees\n\t2 for Radians\n\t3 for Gradians\n\nYour Choice : ";
  int x;
  cin >> x;
  return x;
}

float D_R(float a)
{
  float q = (a / 180);
  float r = q*Pi();
  return r;
}

float G_R(float a)
{
  float q = (a / 200);
  float r = q*Pi();
  return r;
}

float All(float a, float o)
{
  using namespace std;
  std::cout << setprecision(5) << "sin(" << o << ") = " << sin(a) <<     std::endl;
  std::cout << setprecision(5) << "cos(" << o << ") = " << cos(a) << std::endl;
  std::cout << setprecision(5) << "tan(" << o << ") = " << tan(a) << std::endl;
  return 0;
}

int main()
{
  using namespace std;
  int x = Selector();
  cout << "Enter your angle : ";
  float o;
  cin >> o;

  float d = D_R(o);
  float g = G_R(o);

  if (x == 1)
All(d, o);

  else if (x == 2)
All(o, o);
  else if (x == 3)
All(g, o);
  return 0;
}

编辑:

好的,我想到了插入

if (std::abs(sin(a)) < 0.0001) a = 0; 
if (std::abs(cos(a)) < 0.0001) a = 0;
if (std::abs(tan(a)) < 0.0001) a = 0;

在我的 All() 函数之前

这解决了我的问题

C++ 不能为您随意将数字舍入为 0,您可以根据自己的目的定义 "very small number" 的含义。

确定阈值后,您只需要

if (std::abs(number) < THRESHOLD) number = 0;

回复:您的编辑

For cos 90, I want it to be 0 instead of -4.311e-008

同样,由您 来定义阈值。是否要将 0.00000001 四舍五入为 0? 0.0001 呢? 0.1呢? 需要定义发生舍入的行。

可能trunc()如你所愿。

#include <cmath>

cout << roundf(2.2356e-17) << " " << trunc(2.2356e-17) << endl;

输出

0 0

另请参阅:round(), trunc(), nearbyint()