math.h中的函数未返回期望值

时间:2019-10-19 21:57:42

标签: c

我正在编写的程序应该计算以下功能:

f(x,y)= 2 sin(x) + cos(y) - tg(x+y)

我尝试执行以下操作:

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

double toDegrees(double radians){
  return radians * (180.0 / M_PI);
}

int main(void){
  double x,y;
  printf("What's the value of x?\n");
  scanf("%lf", &x);
  printf("What's the value of y?\n");
  scanf("%lf", &y);
  printf("The values are %lf\n", toDegrees(2*sin(x)+cos(y)-tan(x+y)));
  return 0;
}

函数toDegrees将把math.h中函数的默认输出从弧度转换为度。

不带toDegrees功能的弧度的预期输出为-2.07746705002370603998583034482545686045261881310920233482

那确实是输出。

函数toDegrees的预期输出(以度为单位)为1.881737400858622861572140743032864796565271853728846372576

但是,输出为-119.030094

我期望的输出是我在here中通过x=10y=21获得的输出。

为什么会这样,我该如何解决?

我确实把-lm做为编译。

1 个答案:

答案 0 :(得分:2)

这不是编程错误,而是数学错误:触发函数的输入是以度或弧度为单位的角度,而不是输出。另外,转换是错误的方法:您想将度数转换为弧度,而不是将弧度转换为度。

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

double toRadians(double degrees){
  return degrees * (M_PI / 180.0);
}

int main(void){
  double x,y;
  printf("What's the value of x?\n");
  scanf("%lf", &x);
  printf("What's the value of y?\n");
  scanf("%lf", &y);
  printf("The values are %lf\n", 2*sin(toRadians(x))+cos(toRadians(y))+tan(toRadians(x+y)));
  return 0;
}

在解决所有这些错误的情况下,正确输入x的10和y输入21会正确返回您想要的1.881737