微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

以极坐标形式表示的复数总和

如何解决以极坐标形式表示的复数总和

我需要对两个复数 (c1,c2) 求和,然后以极坐标形式表示结果。

我真的不知道如何访问 c1+c2 的结果,我的意思是我将它们存储在变量“result”中,但是当我尝试访问它们时,我发现自己处于 ComplexPolar 结构中,所以我不能访问 result.real 和 result.img 来计算大小和角度:

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

struct ComplexCartesian
{
    float real;
    float img;
};

struct ComplexPolar
{
    float magnitude;
    float angle;
};

struct ComplexPolar add_two_complex(struct ComplexCartesian c1,struct ComplexCartesian c2,struct ComplexPolar result)
{
    result.real= c1.real+c2.real;
    result.img=c1.img+c2.img;

    result.magnitude= sqrt((result.real)^2 + (result.img)^2);
    result.angle= atan2(result.img,result.real);
}

解决方法

^2 不是您在 C 中的平方方式,您必须将数字自乘或使用 libc pow 函数。

^2 是一个 XOR 操作,您的目标是切换第二位,但在您的情况下,您在浮点数上使用它,这违反了严格的别名规则并导致 undefined behavior(在不成为你所寻求的)。

请参阅下面的代码并添加一些注释:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

struct ComplexCartesian
{
    float real;
    float img;
};

struct ComplexPolar
{
    float magnitude;
    float angle;
};

struct ComplexPolar polar_from_cartesian_sum(struct ComplexCartesian c1,struct ComplexCartesian c2)
{
    struct ComplexPolar complexPolar; // here you declare the variable of your ComplexPolar struct

    c1.real += c2.real; // you don't need to have a result var,you can just reuse c1.
    c1.img += c2.img;
    complexPolar.magnitude = sqrt(c1.real * c1.real + c1.img * c1.img);
    complexPolar.angle = atan2(c1.img,c1.real);

    return complexPolar; // you return the value;
}


int main(void) {
    struct ComplexCartesian c1 = {0.12f,0.15f};
    struct ComplexCartesian c2 = {0.42f,1.15f};
    struct ComplexPolar complexPolar = polar_from_cartesian_sum(c1,c2);

    printf("%f %f\n",complexPolar.magnitude,complexPolar.angle);

    return 0;
}

使用 gcc complex.c -lm && ./a.out 编译

输出:

1.407693 1.177098

注意:也许您应该明确指出您的角度以弧度表示,并将您的函数重命名为 polar_from_cartesian_sum

半径 = 1.41
θ = 67.44o = 1.18 弧度

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。