複素数の足し算には、`+`演算子と`complex`モジュールの`add()`メソッドの2つの方法があります。
C言語では、複素数を表す構造体を定義し、その構造体を扱う関数で二つの複素数の和を求めることができます。
#include <stdio.h>
typedef struct complex {
float real;
float imag;
} Complex;
Complex add(Complex c1, Complex c2) {
Complex result;
result.real = c1.real + c2.real;
result.imag = c1.imag + c2.imag;
return result;
}
int main() {
Complex c1, c2, sum;
printf("Enter real and imaginary parts of first complex number: ");
scanf("%f %f", &c1.real, &c1.imag);
printf("Enter real and imaginary parts of second complex number: ");
scanf("%f %f", &c2.real, &c2.imag);
sum = add(c1, c2);
printf("Sum = %.2f + %.2fi\n", sum.real, sum.imag);
return 0;
}
プログラム実行後、実部と虚部をそれぞれ入力するように促し、それらの和を計算して出力します。