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

时间:2015-07-15 15:10:52

标签: c++ rounding

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 cos tan 值。

对于 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;

在我的全部()功能

之前

这解决了我的问题

2 个答案:

答案 0 :(得分:8)

C ++不能随意将数字舍入为0,由你来定义“非常小的数字”是为了你的目的。

确定阈值后,您只需要

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

RE:您的编辑

  

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

同样,由您决定来定义阈值。你想要0.00000001四舍五入为0吗? 0.0001怎么样? 0.1怎么样? 需要定义发生舍入的行。

答案 1 :(得分:0)

可能http://example.com/script.js:1做你想做的事。

trunc()

<强>输出

#include <cmath>

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

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

相关问题