C言語のサンプル - 複素数の加算
構造体(struct)を使用して2つの複素数を加算します。
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("1番目の複素数\n");
printf("実部と虚部を入力してください:\n");
scanf("%f %f", &n1.real, &n1.imag);
printf("\n2番目の複素数\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言語のサンプル