编程题:使用结构体(struct)将两个复数相加。
我们把形如 a+bi(a,b均为实数)的数称为复数,其中 a 称为实部,b 称为虚部,i 称为虚数单位。
第一个复数 输入实部和虚部: 2.3 4.5
第二个复数 输入实部和虚部: 3.4 5 Sum = 5.7 + 9.5i
#include <stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> #include <windows.h> struct img{ double real; double comp; }; int main(void) { struct img com1, com2; puts("请输入第一个虚数的实部和虚部"); scanf("%lf%lf", &com1.real, &com1.comp); puts("请输入第二个虚数的实部和虚部"); scanf("%lf%lf", &com2.real, &com2.comp); if ((com1.comp + com2.comp) >= 0) { printf("Sum=%lf+%lfi\n", com1.real + com2.real, com1.comp + com2.comp); } else { printf("Sum=%lf%lfi\n", com1.real + com2.real, com1.comp + com2.comp); } return 0; }
#include<iostream>
using namespace std;
typedef struct complex
{
double realNumber;
double imaginaryNumber;
}Complex,*ComplexPointer;
ComplexPointer add(Complex & c1,Complex & c2)
ComplexPointer cp=new Complex;
cp->realNumber=c1.realNumber+c2.realNumber;
cp->imaginaryNumber=c1.imaginaryNumber+c2.imaginaryNumber;
return cp;
}
int main()
Complex complexArray[2];
for(int i=0;i<2;i++)
cout<<"ComplexNumber"<<i<<endl;
cout<<"realNumber:\t";
cin>>complexArray[i].realNumber;
cout<<"imaginaryNumber:\t";
cin>>complexArray[i].imaginaryNumber;
ComplexPointer cp=add(complexArray[0],complexArray[1]);
cout<<cp->realNumber<<"+"<<cp->imaginaryNumber<<"i"<<endl;
#include <stdi...
用户登录可进行刷题及查看答案
#include <stdio.h> typedef struct complex { float real; float imag; } complex; complex add(complex n1,complex n2); int main() { complex n1, n2, temp; printf("第一个复数 \n"); printf("输入实部和虚部:\n"); scanf("%f %f", &n1.real, &n1.imag); printf("\n第二个复数 \n"); printf("输入实部和虚部:\n"); scanf("%f %f", &n2.real, &n2.imag); temp = add(n1, n2); printf("Sum = %.1f + %.1fi", temp.real, temp.imag); return 0; } complex add(complex n1, complex n2) { complex temp; temp.real = n1.real + n2.real; temp.imag = n1.imag + n2.imag; return(temp); }
登录后提交答案