C#练习(1~8)源代码下载请到http://download.youkuaiyun.com/detail/hsttmht/3751088
引用请注明http://blog.youkuaiyun.com/hsttmht
实现复数的相加。
using System;
using System.Collections.Generic;
using System.Text;
namespace fushu
{
public struct fushu
{
public int RealPart;//复数的实数部分
public int ImaginPart;//复数的虚数部分
public fushu(int RealPart, int ImaginPart)
{
this.RealPart = RealPart;
this.ImaginPart = ImaginPart;
}
public static fushu operator+(fushu a, fushu b)
{
return new fushu(a.RealPart + b.RealPart, a.ImaginPart + b.ImaginPart);
}
public override string ToString()//扩展或修改继承的方法、属性、索引器或事件的抽象实现或虚实现,必须使用 override 修饰符.override 方法提供从基类继承的成员的新实现。
{
return (String.Format("{0}+{1}i", RealPart, ImaginPart));
}
}
class Testfushu
{
static void Main()
{
fushu num1 = new fushu(6, 7);
fushu num2 = new fushu(8, 9);
fushu complexAdd = num1 + num2;
Console.WriteLine("第一个复数:{0}", num1);
Console.WriteLine("第二个复数:{0}", num2);
Console.WriteLine("两个复数之和:{0}", complexAdd);
Console.ReadKey();
}
}
}
本文介绍了一个简单的C#程序示例,该程序定义了一个复数结构,并实现了复数的加法运算。通过这个例子,读者可以了解如何在C#中自定义结构并重载运算符。
3004





