IHYPRESS.NET
C
HOME | ASP | C | CSS | HTML | JAVASCRIPT | PERL | PHP | PYTHON | RUBY | SVG
CStructures & Linked Lists ❯ Complex Numbers Structure
<10.07>
/* Partial implementation of type and operators for complex numbers. */ #include <stdio.h> #include <math.h> /* User-defined complex number type */ typedef struct { double real, imag; } complex_t; /* complex number input function returns standard scanning error code 1 => valid scan, 0 => error, negative EOF value => end of file */ int scan_complex (complex_t *c) { int status; status = scanf("%lf%lf", &c->real, &c->imag); if (status == 2) status = 1; else if (status != EOF) status = 0; return (status); } /* complex output function displays value as (a + bi) or (a - bi), dropping a or b if they round to 0 unless both round to 0 */ void print_complex (complex_t c) { double a, b; char sign; a = c.real; b = c.imag; printf("("); if (fabs(a) < .005 && fabs(b) < .005) { printf("%.2lf", 0.0); } else if (fabs(b) < .005) { printf("%.2lf", a); } else if (fabs(a) < .005) { printf("%.2lfi", b); } else { if (b < 0) sign = '-'; else sign = '+'; printf("%.2lf %c %.2lfi", a, sign, fabs(b)); } printf(")"); } /* returns the sum of complex values c1 and c2 */ complex_t add_complex (complex_t c1, complex_t c2) { complex_t csum; csum.real = c1.real + c2.real; csum.imag = c1.imag + c2.imag; return (csum); } /* returns the difference of complex values c1 and c2 */ complex_t subtract_complex (complex_t c1, complex_t c2) { complex_t cdiff; cdiff.real = c1.real - c2.real; cdiff.imag = c1.imag - c2.imag; return (cdiff); } /* returns the absolute value of complex number c */ complex_t abs_complex (complex_t c) { complex_t cabs; cabs.real = sqrt(c.real * c.real + c.imag * c.imag); cabs.imag = 0; return (cabs); } int main (void) { complex_t com1, com2; /* Gets the two complex numbers */ printf("Enter the real and imaginary parts of a complex number\n"); printf("separated by a space > "); scan_complex(&com1); printf("Enter a second complex number > "); scan_complex(&com2); /* forms and displays the sum */ printf("\n"); print_complex(com1); printf(" + "); print_complex(com2); printf(" = "); print_complex(add_complex(com1, com2)); /* forms and displays the difference */ printf("\n\n"); print_complex(com1); printf(" - "); print_complex(com2); printf(" = "); print_complex(subtract_complex(com1, com2)); /* forms and displays the absolute value of the first number */ printf("\n\n|"); print_complex(com1); printf("| = "); print_complex(abs_complex(com1)); printf("\n"); return (0); }
Hergestellt in Deutschland / Made in Germany
Enter the real and imaginary parts of a complex number separated by a space > 3.4 2.1 Enter a second complex number > 8.9 4.3 (3.40 + 2.10i) + (8.90 + 4.30i) = (12.30 + 6.40i) (3.40 + 2.10i) - (8.90 + 4.30i) = (-5.50 - 2.20i) |(3.40 + 2.10i)| = (4.00)
COPYRIGHT © 2015-2024 IHYPRESS.NET. A DIVISION OF IHY PRESS. ALL RIGHTS RESERVED.