【问题标题】:c# gives wrong answer to cosc# 对 cos 给出了错误的答案
【发布时间】:2023-02-17 20:43:09
【问题描述】:

该程序需要两个向量之间的角度。

我想得到一个数字的反余弦值,但它以度数和弧度给出了错误的答案,即使在将 rad 添加到 deg 方程之后

dis = 1 / Math.Cos(1); //output: 1.85 它的弧度和度数应该为 0

dis = 1 / Math.Cos(0.5); //output 1.14
dis = (dis * Math.PI) / 180; //output 0.02

正确答案: 以弧度为单位:1.04719755 度数:60

【问题讨论】:

  • 应该是Math.Acos(1)
  • 正如你自己所说——余弦。
  • 余弦的倒数不是 1 / 余弦。此外,对于任何 x 值,您都不能期望 1 / x 为 0。

标签: c# math trigonometry


【解决方案1】:

您正在寻找 Math.Acos,它返回余弦给定值的角度:

double[] tests = new double[] {
  0,
  0.5,
  1.0
};

string result = string.Join(Environment.NewLine, tests
  .Select(test => $"{test,5:f2} : {Math.Acos(test),5:f2} : {Math.Acos(test) * 180 / Math.PI,5:f2} deg"));

Console.Write(result);

输出:

 0.00 :  1.57 : 90.00 deg
 0.50 :  1.05 : 60.00 deg
 1.00 :  0.00 :  0.00 deg

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-13
    • 2011-07-02
    • 1970-01-01
    相关资源
    最近更新 更多