用c#定义描述复数的类,并实现复数的输入和输出。设计三个方法分别完成复数的加、减和乘法运算。请包含适合于入口点的静态 “Main” 方法
时间: 2024-10-25 09:15:01 浏览: 38
在C#中,我们可以定义一个名为`ComplexNumber`的类来表示复数,包括实部(RealPart)和虚部(ImaginaryPart)。以下是一个简单的实现:
```csharp
using System;
public class ComplexNumber
{
public double RealPart { get; set; }
public double ImaginaryPart { get; set; }
// 定义构造函数,初始化复数
public ComplexNumber(double real, double imaginary)
{
RealPart = real;
ImaginaryPart = imaginary;
}
// 输入/输出方法
public override string ToString()
{
return $"({RealPart}, {ImaginaryPart})";
}
// 加法方法
public static ComplexNumber Add(ComplexNumber num1, ComplexNumber num2)
{
double real = num1.RealPart + num2.RealPart;
double imaginary = num1.ImaginaryPart + num2.ImaginaryPart;
return new ComplexNumber(real, imaginary);
}
// 减法方法
public static ComplexNumber Subtract(ComplexNumber num1, ComplexNumber num2)
{
double real = num1.RealPart - num2.RealPart;
double imaginary = num1.ImaginaryPart - num2.ImaginaryPart;
return new ComplexNumber(real, imaginary);
}
// 乘法方法
public static ComplexNumber Multiply(ComplexNumber num1, ComplexNumber num2)
{
double real = num1.RealPart * num2.RealPart - num1.ImaginaryPart * num2.ImaginaryPart;
double imaginary = num1.RealPart * num2.ImaginaryPart + num1.ImaginaryPart * num2.RealPart;
return new ComplexNumber(real, imaginary);
}
}
// 入口点的静态 Main 方法
public static void Main(string[] args)
{
// 创建复数实例
ComplexNumber complex1 = new ComplexNumber(3, 4);
ComplexNumber complex2 = new ComplexNumber(1, -2);
// 输出复数
Console.WriteLine($"复数1: {complex1}");
Console.WriteLine($"复数2: {complex2}");
// 运算并输出结果
ComplexNumber sum = ComplexNumber.Add(complex1, complex2);
Console.WriteLine("两数之和: " + sum);
ComplexNumber difference = ComplexNumber.Subtract(complex1, complex2);
Console.WriteLine("两数之差: " + difference);
ComplexNumber product = ComplexNumber.Multiply(complex1, complex2);
Console.WriteLine("两数之积: " + product);
}
```
这个程序定义了一个复杂的类,包含了加、减、乘的方法,以及一个用于演示如何创建复数并执行基本运算的`Main`方法。运行此代码,你将看到复数的输入输出以及它们之间的运算结果。
阅读全文