写一段拥有两个复数变量且执行一些简单的算术运算的c语言代码
时间: 2024-09-18 16:01:04 浏览: 49
在 C 语言中,我们可以创建结构体来代表复数,并为其定义加法、减法等运算。这里是一个简单的例子:
```c
#include <stdio.h>
typedef struct {
double real; // 实部
double imag; // 虚部
} Complex;
// 定义复数加法函数
Complex addComplex(Complex c1, Complex c2) {
Complex result;
result.real = c1.real + c2.real;
result.imag = c1.imag + c2.imag;
return result;
}
// 定义复数减法函数
Complex subtractComplex(Complex c1, Complex c2) {
Complex result;
result.real = c1.real - c2.real;
result.imag = c1.imag - c2.imag;
return result;
}
int main() {
Complex num1 = {3.0, 4.0}; // 第一个复数 (3+4i)
Complex num2 = {1.0, 2.0}; // 第二个复数 (1+2i)
printf("First complex number: (%f, %fi)\n", num1.real, num1.imag);
printf("Second complex number: (%f, %fi)\n", num2.real, num2.imag);
Complex sum = addComplex(num1, num2); // 计算两数之和
Complex diff = subtractComplex(num1, num2); // 计算两数之差
printf("Sum of the two numbers is: (%f, %fi)\n", sum.real, sum.imag);
printf("Difference of the two numbers is: (%f, %fi)\n", diff.real, diff.imag);
return 0;
}
```
阅读全文