定义复数的类,并实现复数的输入输出。设计三个方法分别完成复数的加、减和乘法运算(用c#语言)
时间: 2024-11-24 20:43:20 浏览: 24
在C#中,我们可以定义一个名为`ComplexNumber`的类来表示复数,并包含两个私有成员变量:实部`real`和虚部`imaginary`。这里是一个简单的实现:
```csharp
public class ComplexNumber
{
private double real;
private double imaginary;
// 构造函数用于初始化复数
public ComplexNumber(double realPart, double imaginaryPart)
{
this.real = realPart;
this.imaginary = imaginaryPart;
}
// 输入输出方法
public override string ToString()
{
return $"({real}, {imaginary})";
}
// 读取输入方法,假设从控制台获取用户输入
public static ComplexNumber FromUserInput(string input)
{
string[] parts = input.Split(',');
return new ComplexNumber(double.Parse(parts[0]), double.Parse(parts[1]));
}
// 复数加法
public ComplexNumber Add(ComplexNumber other)
{
double realSum = this.real + other.real;
double imaginarySum = this.imaginary + other.imaginary;
return new ComplexNumber(realSum, imaginarySum);
}
// 复数减法
public ComplexNumber Subtract(ComplexNumber other)
{
double realDiff = this.real - other.real;
double imaginaryDiff = this.imaginary - other.imaginary;
return new ComplexNumber(realDiff, imaginaryDiff);
}
// 复数乘法
public ComplexNumber Multiply(ComplexNumber other)
{
double realProduct = this.real * other.real - this.imaginary * other.imaginary;
double imaginaryProduct = this.real * other.imaginary + this.imaginary * other.real;
return new ComplexNumber(realProduct, imaginaryProduct);
}
}
```
你可以像下面这样使用这个类:
```csharp
public static void Main(string[] args)
{
Console.Write("请输入第一个复数 (a, b): ");
string input1 = Console.ReadLine();
ComplexNumber num1 = ComplexNumber.FromUserInput(input1);
Console.Write("请输入第二个复数 (c, d): ");
string input2 = Console.ReadLine();
ComplexNumber num2 = ComplexNumber.FromUserInput(input2);
ComplexNumber sum = num1.Add(num2);
ComplexNumber difference = num1.Subtract(num2);
ComplexNumber product = num1.Multiply(num2);
Console.WriteLine($"加法结果: {sum}");
Console.WriteLine($"减法结果: {difference}");
Console.WriteLine($"乘法结果: {product}");
}
```
阅读全文