C语言复数的加减及输出结构体
短信预约 -IT技能 免费直播动态提醒
一、
#include<stdio.h>
typedef struct complex
{
int real; //实部
int imag; //虚部
}complex;
complex complexadd(complex x,complex y)
{
complex sum;
sum.real = x.real + y.real;
sum.imag = x.imag + y.imag;
return sum;
}
complex complexsub(complex x,complex y)
{
complex sum;
sum.real = x.real - y.real;
sum.imag = x.imag - y.imag;
return sum;
}
void printfcomplex(complex x)
{
printf("%d",x.real);
if(x.imag > 0)
{
printf("+");
}
printf("%d\n",x.imag);
}
int main()
{
complex f1 = {3,-5};
complex f2 = {-5,8};
printfcomplex(f1);
printfcomplex(f2);
complex f3 = complexadd(f1,f2);
printfcomplex(complexadd(f1,f2));
printfcomplex(f3);
printfcomplex(complexsub(f1,f2));
return 0;
}
二、分文件
complex.c
#include<stdio.h>
#include"complex.h"
complex complexadd(complex x,complex y)
{
complex sum;
sum.real = x.real + y.real;
sum.imag = x.imag + y.imag;
return sum;
}
complex complexsub(complex x,complex y)
{
complex sum;
sum.real = x.real - y.real;
sum.imag = x.imag - y.imag;
return sum;
}
void printfcomplex(complex x)
{
printf("%d",x.real);
if(x.imag > 0)
{
printf("+");
}
printf("%di\n",x.imag);
}
main.c
#include<stdio.h>
#include"complex.h" // complex 头文件
int main()
{
complex f1 = {3,-5}; // 结构体初始化
complex f2 = {-5,8};
printfcomplex(f1); // 打印复数
printfcomplex(f2);
complex f3 = complexadd(f1,f2);
printfcomplex(complexadd(f1,f2));
printfcomplex(f3);
printfcomplex(complexsub(f1,f2));
return 0;
}
complex.h
#ifndef __COMPLEX_H__
#define __COMPLEX_H__
// 类型声明
typedef struct complex
{
int real; //实部
int imag; //虚部
}complex;
complex complexadd(complex x,complex y);
complex complexsub(complex x,complex y);
void printfcomplex(complex x);
#endif
到此这篇关于C语言复数的加减及输出结构体的文章就介绍到这了,更多相关C语言复数内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341