c 语言 复数基本运算主函数
时间: 2024-09-09 12:10:58 浏览: 36
在C语言中,处理复数的基本运算通常涉及到结构体来表示复数,包含实部和虚部两个成员。这里我们可以创建一个简单的主函数来演示复数的加减乘除运算。首先,我们需要定义一个复数结构体:
```c
#include <stdio.h>
typedef struct {
double real; // 实部
double imag; // 虚部
} complex;
```
接下来,我们定义一些基本运算的函数:
```c
// 加法
complex add(complex a, complex b) {
complex result = {a.real + b.real, a.imag + b.imag};
return result;
}
// 减法
complex subtract(complex a, complex b) {
complex result = {a.real - b.real, a.imag - b.imag};
return result;
}
// 乘法
complex multiply(complex a, complex b) {
double real = a.real * b.real - a.imag * b.imag;
double imag = a.real * b.imag + a.imag * b.real;
complex result = {real, imag};
return result;
}
// 除法
complex divide(complex a, complex b) {
if (b.real == 0 && b.imag == 0) {
printf("Error: Division by zero is not allowed.\n");
return (complex){NaN, NaN}; // 返回不是一个具体的值,表示未定义
}
double denominator = b.real * b.real + b.imag * b.imag;
double real = (a.real * b.real + a.imag * b.imag) / denominator;
double imag = (a.imag * b.real - a.real * b.imag) / denominator;
complex result = {real, imag};
return result;
}
```
然后,在主函数中,你可以创建复数并测试这些操作:
```c
int main() {
complex num1 = {3, 4}; // 示例复数
complex num2 = {1, -2};
complex sum = add(num1, num2);
complex diff = subtract(num1, num2);
complex prod = multiply(num1, num2);
complex quot = divide(num1, num2);
printf("Sum: %f + i%f\n", sum.real, sum.imag);
printf("Difference: %f + i%f\n", diff.real, diff.imag);
printf("Product: %f + i%f\n", prod.real, prod.imag);
printf("Quotient: %f + i%f\n", quot.real, quot.imag);
return 0;
}
```
阅读全文