U ovom ćete primjeru naučiti uzimati dva složena broja kao strukture i dodavati ih stvaranjem korisnički definirane funkcije.
Da biste razumjeli ovaj primjer, trebali biste imati znanje sljedećih C programskih tema:
- C strukt
- C Struktura i funkcija
Dodajte dva složena broja
#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); )
Izlaz
Za 1. kompleksni broj Unesite stvarne i imaginarne dijelove: 2.1 -2.3 Za 2. kompleksni broj Unesite stvarne i imaginarne dijelove: 5.6 23.2 Zbroj = 7.7 + 20.9i
U ovom se programu complex
deklarira imenovana struktura . Ima dva člana: stvarni i imag. Zatim smo iz ove strukture stvorili dvije varijable n1 i n2.
Te dvije strukturne varijable prosljeđuju se add()
funkciji. Funkcija izračunava zbroj i vraća strukturu koja sadrži zbroj.
Konačno, iz main()
funkcije se ispisuje zbroj kompleksnih brojeva .