用 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+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.