课程设计__复数的计算
1、操作符重载
2、这里的复数并没有用class,下一篇会有。
#include <stdio.h> #include <algorithm> #include <iostream> using namespace std; struct Complex { float real; float imag; }; Complex operator +(Complex &a,Complex &b) { Complex c; c.real=a.real+b.real; c.imag=a.imag+b.imag; return c; } Complex operator -(Complex &a,Complex &b) { Complex c; c.real=a.real-b.real; c.imag=a.imag-b.imag; return c; } Complex operator *(Complex &a,Complex &b) { Complex c; c.real=a.real*b.real-a.imag*b.imag; c.imag=a.real*b.imag+a.imag*b.real; return c; } Complex operator /(Complex &a,Complex &b) { float fm; fm=a.real*b.real-a.imag*b.imag;///分母 Complex c; c.real=(a.real*b.real-a.imag*b.imag)/fm; c.imag=(a.real*b.imag+a.imag*b.real)/fm; return c; } void printFormerAdd(Complex &a,Complex &b)///打印加法的原式 { printf("(%.1f ,%.1f i)+(%.1f ,%.1f i)=",a.real,a.imag,b.real,b.imag); } void printFormerSub(Complex &a,Complex &b)///打印减法的原式 { printf("(%.1f ,%.1f i)-(%.1f ,%.1f i)=",a.real,a.imag,b.real,b.imag); } void printFormerMul(Complex &a,Complex &b)///打印乘法的原式 { printf("(%.1f ,%.1f i)*(%.1f ,%.1f i)=",a.real,a.imag,b.real,b.imag); } void printFormerDiv(Complex &a,Complex &b)///打印除法的原式 { printf("(%.1f ,%.1f i)/(%.1f ,%.1f i)=",a.real,a.imag,b.real,b.imag); } void print(Complex c)///打印结果 { printf("(%.1f ,%.1f i)\n",c.real,c.imag); } int main() { Complex a,b,c; printf("This is complex's operation\n"); printf("Please input your wants complex's operation\n"); char o; scanf("%c",&o); system("cls"); switch (o) { case '+': printf("Please input two complex's real and imag\n"); scanf("%f%f",&a.real,&a.imag); scanf("%f%f",&b.real,&b.imag); c=a+b; printFormerAdd(a,b); print(c); break; case '-': printf("Please input two complex's real and imag\n"); scanf("%f%f",&a.real,&a.imag); scanf("%f%f",&b.real,&b.imag); c=a-b; printFormerSub(a,b); print(c); break; case '*': printf("Please input two complex's real and imag\n"); scanf("%f%f",&a.real,&a.imag); scanf("%f%f",&b.real,&b.imag); c=a*b; printFormerMul(a,b); print(c); break; case '/': printf("Please input two complex's real and imag\n"); scanf("%f%f",&a.real,&a.imag); scanf("%f%f",&b.real,&b.imag); c=a/b; printFormerDiv(a,b); print(c); break; } system("pause"); return 0; }