用 C 语言编写程序以相加两个复数


已知有两个复数 a1+ ib1 和 a2 + ib2,任务是相加这两个复数。

复数是可以表达为“a+ib”形式的数,其中“a”和“b”是实数,i 是虚数,即关于表达式 𝑥 2 = −1 的解,因为没有实数满足该方程,所以称其为虚数。

输入 

a1 = 3, b1 = 8
a2 = 5, b2 = 2

输出 

Complex number 1: 3 + i8
Complex number 2: 5 + i2
Sum of the complex numbers: 8 + i10

解释 

(3+i8) + (5+i2) = (3+5) + i(8+2) = 8 + i10

输入 

a1 = 5, b1 = 3
a2 = 2, b2 = 2

输出 

Complex number 1: 5 + i3
Complex number 2: 2 + i2
Sum of the complex numbers: 7 + i5

解释 

(5+i3) + (2+i2) = (5+2) + i(3+2) = 7 + i5

用于解决问题的如下方法

  • 首先声明一个用于存储实数和虚数的结构。

  • 接收输入,并相加所有复数的实数和虚数。

算法

Start
Decalre a struct complexnum with following elements
   1. real
   2. img
In function complexnum sumcomplex(complexnum a, complexnum b)
   Step 1→ Declare a signature struct complexnum c
   Step 2→ Set c.real as a.real + b.real
   Step 3→ Set c.img as a.img + b.img
   Step 4→ Return c
In function int main()
   Step 1→ Declare and initialize complexnum a = {1, 2} and b = {4, 5}
   Step 2→ Declare and set complexnum c as sumcomplex(a, b)
   Step 3→ Print the first complex number
   Step 4→ Print the second complex number
   Step 5→ Print the sum of both in c.real, c.img
Stop

示例

#include <stdio.h>
//structure for storing the real and imaginery
//values of complex number
struct complexnum{
   int real, img;
};
complexnum sumcomplex(complexnum a, complexnum b){
   struct complexnum c;
   //Adding up two complex numbers
   c.real = a.real + b.real;
   c.img = a.img + b.img;
   return c;
}
int main(){
   struct complexnum a = {1, 2};
   struct complexnum b = {4, 5};
   struct complexnum c = sumcomplex(a, b);
   printf("Complex number 1: %d + i%d
", a.real, a.img);    printf("Complex number 2: %d + i%d
", b.real, b.img);    printf("Sum of the complex numbers: %d + i%d
", c.real, c.img);    return 0; }

输出

如果运行以上代码,会生成以下输出 −

Complex number 1: 1 + i2
Complex number 2: 4 + i5
Sum of the complex numbers: 5 + i7

更新日期: 13-Aug-2020

9K+ 浏览量

开启你的 职业生涯

通过完成课程获得认证

开始
广告