tan(90)在c中的值?

时间:2015-07-20 17:26:22

标签: c

它给出的值是557135813.94455。这个价值每次都会保持不变吗?为什么它没有显示出无穷大?

#include <stdio.h>     
#include <math.h>       

#define PI 3.14159265

int main ()
{
  double param, result;
  param = 90.0;
  result = tan ( param * PI / 180.0 );
  printf ("The tangent of %f degrees is %f.\n", param, result );
  return 0;
}

3 个答案:

答案 0 :(得分:7)

你没有传递Pi / 2的值,你传递的是90.0 * 3.14159265 / 180.0,近似值。

答案 1 :(得分:2)

代码不要求90°的正切,而是以弧度为单位的数字的正切接近90°。转换为弧度并不精确,因为π/ 2弧度不能完全表示为double

解决方案是先执行度范围,然后调用tan(d2r(x))

#include <math.h>

static double d2r(double d) {
  return (d / 180.0) * ((double) M_PI);
}

double tand(double x /* degrees */) {
  if (!isfinite(x)) {
    return tan(x);
  } else if (x < 0.0) {
    return -tand(-x);
  }
  int quo;
  double x45 = remquo(fabs(x), 90.0, &quo);
  //printf("%d %f ", quo & 3, x45);
  switch (quo % 4) {
    case 0:
      return tan(d2r(x45));
    case 1:
      return 1.0 / tan(d2r(- x45));
    case 2:
      return -tan(d2r(-x45));
    case 3:
      return -1.0 / tan(d2r(x45));
  }
  return 0.0;
}

#define PI 3.14159265

int main(void) {
  double param, result;
  param = 90.0;
  result = tan(param * PI / 180.0);
  printf("Angle  %.*e radian\n", DBL_DECIMAL_DIG - 1, param * PI / 180.0);
  printf("Pi/2 = 1.5707963267948966192313216916398...\n");
  printf("The tangent of %f degrees is %f.\n", param, result);
  int i;
  for (i = -360; i <= 360; i += 30) {
    printf("The tangent method 1 of %.1f degrees is  %.*e\n", 
        1.0*i, DBL_DECIMAL_DIG - 1, tan(d2r(-i)));
    printf("The tangent method 2 of %.1f degrees is  %.*e\n", 
        1.0*i, DBL_DECIMAL_DIG - 1, tand(-i));
  }
  return 0;
}

OP的输出

Angle  1.5707963250000001e+00 radian
Pi/2 = 1.5707963267948966192313216916398...
The tangent of 90.000000 degrees is 557135183.943528.

更好的结果

The tangent method 1 of -360.0 degrees is  -2.4492935982947064e-16
The tangent method 2 of -360.0 degrees is  0.0000000000000000e+00
The tangent method 1 of -330.0 degrees is  -5.7735026918962640e-01
The tangent method 2 of -330.0 degrees is  -5.7735026918962573e-01
The tangent method 1 of -300.0 degrees is  -1.7320508075688770e+00
The tangent method 2 of -300.0 degrees is  -1.7320508075688774e+00
The tangent method 1 of -270.0 degrees is  5.4437464510651230e+15
The tangent method 2 of -270.0 degrees is  -inf
The tangent method 1 of -240.0 degrees is  1.7320508075688752e+00
The tangent method 2 of -240.0 degrees is  1.7320508075688774e+00
The tangent method 1 of -210.0 degrees is  5.7735026918962540e-01
The tangent method 2 of -210.0 degrees is  5.7735026918962573e-01
The tangent method 1 of -180.0 degrees is  -1.2246467991473532e-16
The tangent method 2 of -180.0 degrees is  0.0000000000000000e+00
...

答案 2 :(得分:1)

浮点运算不是精确算术。您甚至无法使用==比较两个浮点数;例如0.6 / 0.2 - 3 == 0应该是正确的,但在大多数系统上它都是错误的。执行浮点计算时要小心,并期望得到准确的结果;这注定要失败。考虑每个浮点计算仅返回近似值;虽然是非常好的,有时甚至是精确的,但不要完全依赖它。