在C语言中,可以使用结构体来表示复数,并定义相应的运算函数来处理复数的浮点运算。以下是一个简单的示例代码:
#includetypedef struct { double real; double imag; } Complex; Complex add(Complex c1, Complex c2) { Complex result; result.real = c1.real + c2.real; result.imag = c1.imag + c2.imag; return result; } Complex subtract(Complex c1, Complex c2) { Complex result; result.real = c1.real - c2.real; result.imag = c1.imag - c2.imag; return result; } Complex multiply(Complex c1, Complex c2) { Complex result; result.real = c1.real * c2.real - c1.imag * c2.imag; result.imag = c1.real * c2.imag + c1.imag * c2.real; return result; } void printComplex(Complex c) { printf("%.2f + %.2fi\n", c.real, c.imag); } int main() { Complex c1 = {3.0, 4.0}; Complex c2 = {1.0, 2.0}; Complex sum = add(c1, c2); Complex difference = subtract(c1, c2); Complex product = multiply(c1, c2); printf("Sum: "); printComplex(sum); printf("Difference: "); printComplex(difference); printf("Product: "); printComplex(product); return 0; }
在上面的代码中,定义了一个Complex
结构体来表示复数,然后定义了三个函数来实现复数的加法、减法和乘法运算。在main
函数中,创建了两个复数c1
和c2
,并调用相应的函数来进行运算,并输出结果。