V tem primeru se boste naučili jemati dve zapleteni številki kot strukturi in ju dodajati z ustvarjanjem uporabniško določene funkcije.
Če želite razumeti ta primer, morate poznati naslednje teme programiranja C:
- C strukt
- C Struktura in funkcija
Dodajte dve kompleksni številki
#include typedef struct complex ( float real; float imag; ) complex; complex add(complex n1, complex n2); int main() ( complex n1, n2, result; printf("For 1st complex number "); printf("Enter the real and imaginary parts: "); scanf("%f %f", &n1.real, &n1.imag); printf("For 2nd complex number "); printf("Enter the real and imaginary parts: "); scanf("%f %f", &n2.real, &n2.imag); result = add(n1, n2); printf("Sum = %.1f + %.1fi", result.real, result.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); )
Izhod
Za 1. kompleksno število vnesite realne in namišljene dele: 2.1 -2.3 Za 2. kompleksno število vnesite realne in namišljene dele: 5.6 23.2 Vsota = 7.7 + 20.9i
V tem programu complex
je navedena struktura z imenom . Ima dva člana: real in imag. Nato smo iz te strukture ustvarili dve spremenljivki n1 in n2.
Ti dve strukturni spremenljivki se preneseta v add()
funkcijo. Funkcija izračuna vsoto in vrne strukturo, ki vsebuje vsoto.
Na koncu se iz main()
funkcije natisne vsota kompleksnih števil .