【问题标题】:Confused about why this part of the code is necessary?对为什么这部分代码是必要的感到困惑?
【发布时间】:2012-08-22 10:35:11
【问题描述】:

以下是将笛卡尔坐标转换为极坐标的代码。 else if 语句 (y>0) = pi/2 else -pi/2 ... 这两行的相关性是什么?当然,您只需要 theta = atan(y/x) 和 r = sqrt(x^2 + y^2) 来确定正确的 theta 和 r? 当我进入调试并放置检查点以查看代码如何运行时,似乎这部分也从未使用过......

有人可以阐明这些行的相关性吗?

谢谢。

这是应用程序的代码;

    void cartesianToPolar (float x, float y, double *rPtr, double *thetaPtr)
{
    //store radius in supplied address - calc for r
    *rPtr = sqrt(x * x + y * y);

    //calc theta
    float theta;
    if (x == 0.0) {
        if (y== 0.0) {
            theta = 0.0;
        } else if ( y > 0){
        theta = M_PI_2;
    } else {
        theta = -M_PI_2;
    }
    }else{
        theta = atan(y/x);
    }
        //store theta in address
        *thetaPtr = theta;
    }
int main (int argc, const char * argv[])
{
    double pi = 3.14;
    double integerPart;
    double fractionPart;

    // Pass add of integerPart as argument
    fractionPart = modf(pi, &integerPart);
    // Find value stored in intpart
    printf("integerPart = %.0f, fractionPart = %.2f\n", integerPart, fractionPart);

    double x = 3.0;
    double y = -4.0;
    double radius;
    double angle;

    cartesianToPolar(x,y,&angle,&radius);
    printf("(%.2f, %.2f) becomes (%.2f radiants, %.2f)\n", x, y, radius, angle);

    return 0;
}

【问题讨论】:

  • 请考虑更改您的标签。其中没有太多objective-c,而是标准c,您可能希望用“极坐标”标记它。
  • 对不起,你说它的c与objective-c相反是正确的。

标签: c polar-coordinates


【解决方案1】:

这个测试在 x==0 时调用(在这种情况下你不能做 y/x),它决定点是向上还是向下(因此角度是 PI/2 或 -PI/2 )。

也许你对糟糕的缩进感到困惑。应该是:

if (x == 0.0) {
    if (y == 0.0) {
        theta = 0.0;
    } else if ( y > 0){
        theta = M_PI_2;
    } else {
        theta = -M_PI_2;
    }
}

【讨论】:

  • 是的,我认为确实如此。所以这实际上是在说... if x==0 跳到 else if (y >0) 以防止代码吐出 'undefined,因为任何除以 0 的东西都趋于无穷大。
  • 让我感到困惑的是,我认为这是在 theta ==0.0 中处理的(因为这也是为了防止它趋于无穷大)
  • 是的。当 x==0 时,您不能使用 atan 方式,但解决方案只是三个可能值之一(第一个,theta=0,有点特殊,因为这主要是一种约定)。
  • 很抱歉添加一连串的 cmets - 我现在完全明白了。我认为将来需要使我的代码更具可读性。
  • 不用担心。在尝试解释代码之前,请务必花时间(重新)缩进代码,这有助于避免许多错误。
【解决方案2】:

如果 x 等于 0 语句

theta = atan(y/x);

将除以零例外。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    相关资源
    最近更新 更多