簡體   English   中英

math.h 中的函數不返回預期值

[英]Functions in math.h don't return the expected value

我正在制作的程序應該計算以下 function:

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;
}

function toDegrees 會將 math.h 中函數的默認 output 從弧度轉換為度數。

沒有 function toDegrees 的弧度中的預期 output 為-2.07746705002370603998583034482545686045261881310920233482

那確實是 output。

預期的 output 度數與 function 度數為1.881737400858622861572140743032864796565271853728846372576

然而,output 是-119.030094

我期待的 output 是我在這里得到的x=10y=21output

為什么會發生這種情況,我該如何解決?

我確實把 -lm 是編譯。

這不是編程錯誤,而是數學錯誤:三角函數的輸入是以度或弧度為單位的角度,而不是輸出。 此外,您的轉換方式是錯誤的:您想將度數轉換為弧度,而不是將弧度轉換為度數。

#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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM