C#数学,给出了错误的结果 [英] C# math, giving wrong result
本文介绍了C#数学,给出了错误的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码:
My code:
using System;
namespace PolarToCart
{
class Program
{
static void Main(string[] args)
{
double r;
double θ;
double ϕ;
string result = "";
r = 1.0;
θ = 2.0;
ϕ = 3.0;
result = Convert.ToString(
r * Math.Sin(θ) * Math.Cos(ϕ)
);
Console.WriteLine(result);
Console.ReadKey();
}
}
}
给我结果:
-0.900197629735517
但是,在我的计算器(和其他计算器)上计算的正确结果是:
0.03485166816
我不知道这里发生了什么。有人有什么见解吗?
谢谢!
我的尝试:
我试图尝试使用括号,而我的数学 - 更好的一半,(有一些编程经验),也是难过的。一些谷歌搜索是自然尝试的
Gives me the result:
-0.900197629735517
However, the correct result, when it's calculated on my calculator, (and other calculators), is:
0.03485166816
I've no idea what's going on here. Does somebody have any insights?
Thank you!
What I have tried:
I've tried to experiment with parenthesizes, and my math-wiz better half, (who has had some programming experience), is also stumped. Some googling was naturally tried
推荐答案
三角函数的参数是弧度。如果您的输入是度数,则必须除以2 * Pi:
The arguments to the trigonometric functions are in radians. If your input is in degrees, you must divide by 2 * Pi:
result = Convert.ToString(
r * Math.Sin(θ / (2 * Math.PI)) * Math.Cos(ϕ / (2 * Math.PI))
);
使用了错误因素。
Used thew wrong factor.
result = Convert.ToString(
r * Math.Sin(Math.PI / 180 * θ) * Math.Cos(Math.PI / 180 * ϕ)
);
[/ EDIT]
[/EDIT]
我同意它: https://www.wolframalpha.com/input/?i=1.0+*+Sin(2.0)+ * + Cos(3.0) [ ^ ]
Wolfram alpha同意。
和我的计算器一样(夏普EL-5020)
你确定吗你的计算器不是假设θ和φ是度,而不是弧度,比如我的计算器,Wolfram Alpha和.NET?
And I'd agree with it: https://www.wolframalpha.com/input/?i=1.0+*+Sin(2.0)+*+Cos(3.0)[^]
Wolfram alpha agrees.
As does my calculator (Sharp EL-5020)
Are you sure your calculators aren't assuming that θ and ϕ are in degrees, rather than radians, like my calculator, Wolfram Alpha, and .NET?
固定代码:
The fixed code:
using System;
namespace PolarToCart
{
class Program
{
public double ConvertToRadians(double angle)
{
return (Math.PI / 180) * angle;
}
static void Main(string[] args)
{
double r;
double θ;
double ϕ;
string result = "";
r = 1.0;
θ = 2.0;
ϕ = 3.0;
result = Convert.ToString(
r * Math.Sin((Math.PI / 180) * θ) * Math.Cos((Math.PI / 180) * ϕ)
);
Console.WriteLine(result);
Console.ReadKey();
}
}
}
这篇关于C#数学,给出了错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文