How to output complex numbers in the C language?
In C language, complex numbers can be represented and operated on using a complex structure. Typically, a complex structure includes both real and imaginary parts.
Here is an example showing how to define and output a complex number.
#include <stdio.h>
typedef struct {
double real; // 实部
double imag; // 虚部
} Complex;
void printComplex(Complex c) {
if (c.imag >= 0) {
printf("%.2f + %.2fi\n", c.real, c.imag);
} else {
printf("%.2f - %.2fi\n", c.real, -c.imag);
}
}
int main() {
Complex c = {2.5, -1.3};
printComplex(c);
return 0;
}
The output is:
2.50 - 1.30i
In the example above, we first define a complex structure Complex that consists of two member variables, representing the real and imaginary parts. Next, we define a function printComplex which is used to display the real and imaginary parts of the complex number. In the main function, we create a complex object called c and then call the printComplex function to output the values of the complex number.
When outputting complex numbers, we use the printf function for formatting. If the imaginary part is greater than or equal to 0, it will be displayed as real part + imaginary part i; if the imaginary part is less than 0, it will be displayed as real part – (-imaginary part) i. The formatting output using the printf function can be adjusted according to the actual situation.