C 語言實例 - 複數相加
使用結構體(struct)將兩個複數相加。
我們把形如 a+bi(a,b均為實數)的數稱為複數,其中 a 稱為實部,b 稱為虛部,i 稱為虛數單位。
實例
#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);
}
輸出結果為:
第一個複數 輸入實部和虛部: 2.3 4.5 第二個複數 輸入實部和虛部: 3.4 5 Sum = 5.7 + 9.5i

 C 語言實例