复数加减运算

来源:互联网 发布:15年最流行网络的歌曲 编辑:程序博客网 时间:2024/05/11 04:09

//完成时间:2014年12月12日
//问题描述:(1)设计复数类Complex,计算两个复数之和、差,同时以 a+bi 的字符串形式显示。 (2)使用复数类Complex验证两个复数 1+2i 和3+4i 相加产生一个新的复数 4+6i ,相减产生一个新的复数 -2-2i


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication32
{
    class Program
    {    
        
        
        static void Main(string[] args)
        {


            complex num1 = new complex(1, 2);
            complex num2 = new complex(3, 4);
            complex complexAdd = num1 + num2;
            complex complexreduce =  num1 - num2;


            Console.WriteLine("第一个复数:{0}", num1);
            Console.WriteLine("第二个复数:{0}", num2);
            Console.WriteLine("两个复数之和:{0}", complexAdd);
            Console.WriteLine("两个复数之差:{0}", complexreduce);
            Console.ReadLine();
        }
    }      
            class  complex
            {
                public double RealPart;
                public double ImaginPart;
                public complex(double RealPart, double ImaginPart)
            {     
                this.RealPart = RealPart;
                this.ImaginPart = ImaginPart;
            }
                public static complex operator +(complex a, complex b)
                {
                    return new complex(a.RealPart + b.RealPart, a.ImaginPart + b.ImaginPart);
                    //return new complex(a.RealPart - b.RealPart, a.ImaginPart - b.ImaginPart);
                }
                public static complex operator -(complex a, complex b)
                {
                    return new complex(a.RealPart - b.RealPart, a.ImaginPart - b.ImaginPart);
                }
                    
                
                 public override string ToString()
                 {
                     return (String.Format("{0}+{1}i", RealPart, ImaginPart));
                     return (String.Format("{0}-{1}i", RealPart, ImaginPart));
                    
                 }
                
 
            }
               
        }


0 0
原创粉丝点击