编程(C#)
(1)定义一个复数类Complex,(2)对运算符进行重载,以完成复数的加减乘除。(3)设计函数Main()测试之。
(1)定义一个复数类Complex,(2)对运算符进行重载,以完成复数的加减乘除。(3)设计函数Main()测试之。
答案:
using System;
using System.Collections.Generic;
using System.Text;namespace ConsoleApplication1
{
class Complex
{
public double Real { get; set; }
public double Com { get; set; }public Complex(double real, double com)
{
Real = real;
Com = com;
}public static Complex operator +(Complex c1, Complex c2)
{
double real = c1.Real + c2.Real;
double com = c1.Com + c2.Com;
return new Complex(real, com);
}public static Complex operator -(Complex c1, Complex c2)
{
double real = c1.Real - c2.Real;
double com = c1.Com - c2.Com;
return new Complex(real, com);
}public static Complex operator *(Complex c1, Complex c2)
{
double real = c1.Real * c2.Real - c1.Com * c2.Com;
double com = c1.Com * c2.Real + c1.Real * c2.Com;
return new Complex(real, com);
}public static Complex operator /(Complex c1, Complex c2)
{
double real = (c1.Real * c2.Real + c1.Com * c2.Com) / (c1.Com * c1.Com + c2.Com * c2.Com);
double com = (c1.Com * c2.Real - c1.Real * c2.Com) / (c1.Com * c1.Com + c2.Com * c2.Com);
return new Complex(real, com);
}//指定输出格式(重写)
public override string ToString()
{
if (Real == 0)
{
return Com + "i";
}
else if (Com == 0)
{
return Real.ToString();
}
else if (Com > 0)
{
return Real + "+" + Com + "i";
}
else
{
return Real.ToString() + Com + "i";
}
}
}
class Program
{
static void Main(string[] args)
{
Complex c1 = new Complex(1, 2);
Complex c2 = new Complex(3, 4);
Console.WriteLine(c1 + c2);
Console.WriteLine(c1 - c2);
Console.WriteLine(c1 * c2);
Console.WriteLine(c1 / c2);
}
}
}
上一个:求用C#编程圆周率,精确到小数后6位的答案
下一个:想学C#高级编程