这篇“怎么用C语言代码实现复数的加减及输出结构体”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“怎么用C语言代码实现复数的加减及输出结构体”文章吧。
一、复数的加减
#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语言代码实现复数的加减及输出结构体”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注编程网行业资讯频道。