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

Jeb*_*hew -5 c++ rounding

在C++中是否有任何命令可以制作,

1.354322e-23
Run Code Online (Sandbox Code Playgroud)

0
Run Code Online (Sandbox Code Playgroud)

这是我的(简单)程序

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

int main()
{
    float x;
    std::cin >> x;
    std::cout << x << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

当我输入值时,

2.2356e-17
Run Code Online (Sandbox Code Playgroud)

它给,

2.2356e-017
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

编辑:

好的我想出了插入

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;
Run Code Online (Sandbox Code Playgroud)

在我的All()函数之前

这解决了我的问题

mea*_*gar 8

C++不能随意将数字舍入为0,由你来定义"非常小的数字"是出于何种目的.

一旦确定了阈值,您就需要

if (std::abs(number) < THRESHOLD) number = 0;
Run Code Online (Sandbox Code Playgroud)

RE:你的编辑

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

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