数据结构复数运算的程序代码
时间: 2023-10-20 12:33:56 浏览: 136
数据结构算法的程序代码
以下是一个用于复数运算的程序代码:
```c
#include <stdio.h>
// 定义一个结构体数组
struct complex{
double a;
double b;
};
// 复数相加
struct complex add(struct complex c1, struct complex c2){
struct complex result;
result.a = c1.a + c2.a;
result.b = c1.b + c2.b;
return result;
}
// 复数相减
struct complex subtract(struct complex c1, struct complex c2){
struct complex result;
result.a = c1.a - c2.a;
result.b = c1.b - c2.b;
return result;
}
// 复数相乘
struct complex multiply(struct complex c1, struct complex c2){
struct complex result;
result.a = c1.a * c2.a - c1.b * c2.b;
result.b = c1.a * c2.b + c1.b * c2.a;
return result;
}
// 输出复数
void printComplex(struct complex c){
if(c.a == 0 && c.b == 0){
printf("0\n");
}else{
if(c.a == 0){
printf("%lfi\n",c.b);
}else if(c.b == 0){
printf("%lf\n",c.a); }else{
if(c.b < 0){
printf("%lf%lfi\n",c.a,c.b);
}else{
printf("%lf+%lfi\n",c.a,c.b);
}
}
}
}
int main() {
struct complex c1 = {3, 4};
struct complex c2 = {1, -2};
struct complex sum = add(c1, c2);
struct complex difference = subtract(c1, c2);
struct complex product = multiply(c1, c2);
printf("Sum: ");
printComplex(sum);
printf("Difference: ");
printComplex(difference);
printf("Product: ");
printComplex(product);
return 0;
}
```
这个程序定义了一个结构体数组用于存储复数,并实现了复数的加法、减法和乘法运算。通过调用相应的函数,可以对复数进行运算并打印结果。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [数据结构基础篇》》用c语言实现复数的八个基本运算](https://blog.csdn.net/weixin_54201782/article/details/128353317)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文