简体   繁体   English

Pi输出迅速

[英]Pi Output In Swift

I am trying to build a degrees/radians calculator. 我正在尝试建立一个度数/弧度计算器。 Here are the functions I have. 这是我的功能。

func degreesToRadians(degrees: Double) -> Double {

    return degrees * (M_PI / 180)

}

func radiansToDegrees(radians: Double) -> Double {

    return radians * (180 / M_PI)

}

degreesToRadians(90)

radiansToDegrees(M_PI/4)

degreesToRadians(90) returns 1.5707963267949 radiansToDegrees(M_PI/4) returns 45.0 DegreesToRadians(90)返回1.5707963267949 radiansToDegrees(M_PI / 4)返回45.0

What I want to happen is in the Degrees to Radians function instead of 1.5707963267949 I want the output to be π/2. 我想发生的是度数弧度函数,而不是1.5707963267949,我希望输出为π/ 2。 Is this even possible? 这有可能吗?

Thanks. 谢谢。

If you want exactly: "π/2", I don't think this is possible with double. 如果您确实要:“π/ 2”,我认为不可能使用double来实现。 You might get this in String, but not in a number. 您可能会以String形式获取此内容,但不能以数字形式获取。 I think your best option would be to take an optional bool in which case result is returned as multiple of pi. 我认为您最好的选择是采用可选布尔值,在这种情况下,结果将以pi的倍数形式返回。

degreesToRadians(90, resultAsMultipleOfPi:true)

If this bool is true then 0.5 should be returned. 如果此布尔值为true,则应返回0.5。 You may need to do some rounding off to get well rounded numbers. 您可能需要进行一些舍入以获得良好的舍入数字。

If you look closely on what is really M_PI you will see that it is predefined double value in math.h that equals 如果仔细查看真正的M_PI您会发现它是math.h中预定义的double值,等于

#define M_PI        3.14159265358979323846264338327950288   /* pi             */

If you want more precision you can declare and use long double value instead. 如果要提高精度,可以声明并使用long double值。

To represent 90 degrees as π/2 , what you want to do is 要将90度表示为π/2 ,您要做的是

  • consider the fraction of degrees over 180 (ie numerator of degrees and denominator of 180 ); 考虑degrees超过180的分数(即degrees分子和180分母);

  • reduce this fraction (ie divide both the numerator and denominator by the greatest common factor ); 减少该分数(即分子和分母都除以最大公因数 ); in the case of 90/180 , the greatest common factor is, in fact, 90 , yielding a reduced numerator of 1 and a reduced denominator of 2 ; 90/180的情况下,最大的公因数实际上是90 ,其分子的简化分母为1 ,分母的分母为2

  • the result as a string representation of the fraction, ie something like 结果以分数的字符串表示形式,即类似

     "\\(reducedNumerator)π/\\(reducedDenominator)" 

    Obviously, if either the numerator or denominator are 1 , then you can suppress that portion of the string, but hopefully you get the basic idea. 显然,如果分子或分母为1 ,则可以抑制字符串的该部分,但希望您能掌握基本原理。

Take a crack at that. 对此表示怀疑。

You can directly use M_PI constant. 您可以直接使用M_PI常量。

If you need in float format just use this, 如果您需要浮点格式,请使用此格式,

let pi = Float(M_PI)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM