定义一个结构,并编写程序,完成复数的加、减、乘、除运算
时间: 2024-09-28 16:11:49 浏览: 30
java编写一个类,该类可以进行加、减、乘、除四则运算,并且输出运算结果
在C++中,我们可以创建一个名为Complex的结构体来表示复数,包含实部和虚部两个成员变量。然后我们编写函数来进行复数的加、减、乘、除操作。以下是简单的示例:
```cpp
// 定义结构体 Complex 表示复数
struct Complex {
double real; // 实部
double imag; // 虚部
};
// 加法运算
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;
}
// 除法运算 (假设除数非零)
Complex divide(Complex c1, Complex c2) {
double denominator = c2.real * c2.real + c2.imag * c2.imag;
if (denominator != 0) {
Complex result;
result.real = (c1.real * c2.real + c1.imag * c2.imag) / denominator;
result.imag = (c1.imag * c2.real - c1.real * c2.imag) / denominator;
return result;
} else {
throw std::invalid_argument("Divisor cannot be zero");
}
}
int main() {
Complex num1 = {3.0, 4.0}; // 复数 3 + 4i
Complex num2 = {1.0, 2.0}; // 复数 1 + 2i
Complex sum = add(num1, num2);
Complex diff = subtract(num1, num2);
Complex prod = multiply(num1, num2);
try {
Complex quotient = divide(num1, num2);
std::cout << "Sum: " << sum.real << "+" << sum.imag << "i\n";
std::cout << "Difference: " << diff.real << "+" << diff.imag << "i\n";
std::cout << "Product: " << prod.real << "+" << prod.imag << "i\n";
std::cout << "Quotient: " << quotient.real << "+" << quotient.imag << "i\n";
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << '\n';
}
return 0;
}
```
这个程序首先定义了复数结构以及相关的运算函数,然后在main函数中实例化复数并展示各种运算结果。
阅读全文