如何向 c 語言函式中傳遞結構體來新增兩個複數?


為了在 C 程式語言中新增兩個複數,使用者必須將兩個複數作為結構成員,並透過建立使用者自定義函式對這兩個數字執行加法運算。

演算法

請參閱下文所給出的用於新增兩個複數的演算法。

Step 1: Declare struct complex with data members.
Step 2: Declare name for structure and variables.
Step 3: Enter real and imaginary part for first complex number at run time.
Step 4: Enter real and imaginary part for second complex number at runtime
Step 5: Compute addition of number1 and number2 by calling function. Go to step 7.
Step 6: Print the result.
Step 7: Compute addition
  • Declare temp variable
  • temp.real = num1.real + num2.real;
  • temp.imag = num1.imag + num2.imag;
  • return (temp);

示例

以下是透過向函式傳遞結構體以新增兩個複數的 C 語言程式 -

 演示

#include <stdio.h>
typedef struct complex{
   float real;
   float imag;
} complex;
complex addition(complex num1, complex num2);
int main(){
   complex num1, num2, value;
   printf("entering real and imag parts of first complex no:
");    scanf("%f %f", &num1.real, &num1.imag);    printf("entering real and imag parts of second complex no:
");    scanf("%f %f", &num2.real, &num2.imag);    value= addition(num1, num2);    printf("result = %.1f + %.1fi", value.real, value.imag);    return 0; } complex addition(complex num1, complex num2){    complex temp;    temp.real = num1.real + num2.real;    temp.imag = num1.imag + num2.imag;    return (temp); }

輸出

當以上程式執行時,它生成以下結果 -

entering real and imag parts of first complex no:
entering real and imag parts of second complex no:
result = 0.0 + 0.0i

更新於: 2021 年 3 月 24 日

6K+ 瀏覽

開啟您的 職業

完成課程,獲取認證

開始學習
廣告
© . All rights reserved.