C++程式:透過傳遞結構體到函式來新增複數


複數是表示為 a+bi 的數,其中 i 是虛數單位,a 和 b 是實數。一些複數的例子如下:

2+5i
3-9i
8+2i

透過傳遞結構體到函式來新增複數的程式如下所示:

示例

 即時演示

#include <iostream>

using namespace std;
typedef struct complexNumber {
   float real;
   float imag;
};
complexNumber addCN(complexNumber num1,complexNumber num2) {
   complexNumber temp;
   temp.real = num1.real + num2.real;
   temp.imag = num1.imag + num2.imag;
   return(temp);
}
int main() {
   complexNumber num1, num2, sum;
   cout << "Enter real part of Complex Number 1: " << endl;

   cin >> num1.real;
   cout << "Enter imaginary part of Complex Number 1: " << endl;

   cin >> num1.imag;
   cout << "Enter real part of Complex Number 2: " << endl;

   cin >> num2.real;
   cout << "Enter imaginary part of Complex Number 2: " << endl;

   cin >> num2.imag;
   sum = addCN(num1, num2);

   if(sum.imag >= 0)
   cout << "Sum of the two complex numbers is "<< sum.real <<" + "<< sum.imag <<"i";
   else
   cout << "Sum of the two complex numbers is "<< sum.real <<" + ("<< sum.imag <<")i";
   return 0;
}

輸出

以上程式的輸出如下所示:

Enter real part of Complex Number 1: 5
Enter imaginary part of Complex Number 1: -9
Enter real part of Complex Number 2: 3
Enter imaginary part of Complex Number 2: 6
Sum of the two complex numbers is 8 + (-3)i

在以上程式中,結構體 complexNumber 包含複數的實部和虛部。如下所示:

struct complexNumber {
   float real;
   float imag;
};

函式 addCN() 接收兩個 complexNumber 型別的引數,並新增這兩個數的實部和虛部。然後,將新增後的值返回到 main() 函式。如下所示:

complexNumber addCN(complexNumber num1,complexNumber num2) {
   complexNumber temp;
   temp.real = num1.real + num2.real;
   temp.imag = num1.imag + num2.imag;
   return(temp);
}

在 main() 函式中,從使用者獲取數字的值。如下所示:

cout << "Enter real part of Complex Number 1: " << endl;
cin >> num1.real;
cout << "Enter imaginary part of Complex Number 1: " << endl;
cin >> num1.imag;

cout << "Enter real part of Complex Number 2: " << endl;
cin >> num2.real;
cout << "Enter imaginary part of Complex Number 2: " << endl;
cin >> num2.imag;

透過呼叫 addCN() 函式獲得兩個數的和。然後列印該和。如下所示:

sum = addCN(num1, num2);
if(sum.imag >= 0)
cout << "Sum of the two complex numbers is "<< sum.real <<" + "<< sum.imag <<"i";

else
cout << "Sum of the two complex numbers is "<< sum.real <<" + ("<< sum.imag <<")i";

更新於: 2020年6月25日

666 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.