利用函数和结构体实现复数的计算

#include <stdio.h>

struct complex{
    int real;
    int imag;
};

struct complex multiply(struct complex x, struct complex y);

int main()
{
    struct complex product, x, y;

    scanf("%d%d%d%d", &x.real, &x.imag, &y.real, &y.imag);
    product = multiply(x, y);
    printf("(%d+%di) * (%d+%di) = %d + %di\n", 
            x.real, x.imag, y.real, y.imag, product.real, product.imag);

    return 0;
}

struct complex multiply(struct complex x, struct complex y){
	struct complex s;
	s.real=x.real*y.real-x.imag*y.imag;
	s.imag=x.real*y.imag+x.imag*y.real;
	return s;
	//这和调用函数很类似,只不过类型由最简单的int转变为结构体struct complex
	//而multiply是这个函数的名字,用来承载结果的时候需要定义一个新的struct complex型的变量
	//自己糊里糊涂犯错误直接用函数名计算了,导致编译错误 
}
//也就是每出现此结构体类型的,就代表该变量具有结构体中的所有属性!!! 
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
结构可以用来定义一个复数类型,使用结构的员变量来存储实部和虚部。下面是一个使用结构实现复数运算的示例: ```c #include <stdio.h> typedef struct { double real; double imaginary; } Complex; // 加法运算 Complex add(Complex a, Complex b) { Complex result; result.real = a.real + b.real; result.imaginary = a.imaginary + b.imaginary; return result; } // 减法运算 Complex subtract(Complex a, Complex b) { Complex result; result.real = a.real - b.real; result.imaginary = a.imaginary - b.imaginary; return result; } // 乘法运算 Complex multiply(Complex a, Complex b) { Complex result; result.real = (a.real * b.real) - (a.imaginary * b.imaginary); result.imaginary = (a.real * b.imaginary) + (a.imaginary * b.real); return result; } // 打印复数 void printComplex(Complex c) { printf("%.2f + %.2fi\n", c.real, c.imaginary); } int main() { Complex a = {3.5, 2.5}; Complex b = {2.0, 1.5}; Complex sum = add(a, b); printf("Sum: "); printComplex(sum); Complex difference = subtract(a, b); printf("Difference: "); printComplex(difference); Complex product = multiply(a, b); printf("Product: "); printComplex(product); return 0; } ``` 在上述代码中,我们定义了一个名为`Complex`的结构,包含了实部和虚部两个成员变量。然后,我们实现了加法、减法和乘法运算的函数,并在`main`函数中演示了如何使用这些函数进行复数运算。最后,我们定义了一个打印复数的辅助函数`printComplex`来方便输出结果。 运行以上代码,将会得到以下输出: ``` Sum: 5.50 + 4.00i Difference: 1.50 + 1.00i Product: 4.75 + 9.25i ``` 这是使用结构实现复数运算的一个简单示例,你可以根据自己的需求扩展和修改代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值