1. 程式人生 > 其它 >C#:(複數類)構建一個複數類,實現複數的加減乘除

C#:(複數類)構建一個複數類,實現複數的加減乘除

技術標籤:C#c#

一、執行效果截圖

二、實驗要求

例:

複數類:

構建一個複數類,實現複數的加減乘除。

三、程式碼示例

using System;
namespace ConsoleApp7
{
    class Program
    {
        static void Main(string[] args)
        {
            Complex x1 = new Complex(2, 3);
            Complex x2 = new Complex(5.6, 7.8);
            Complex x3 = x1.Add(x2);
            x3.show();
            Complex x4 = Complex.Add(x1, x2);
            x4.show();

            Console.ReadLine();
        }
    }
    //複數類
    public class Complex
    {
        private double real;
        private double image;
        public Complex()
        {
            real = image = 0;
        }
        public Complex (double real,double image)
        {
            this.real = real;
            this.image = image;
        }
        public void Set(double real,double image)
        {
            this.real = real;
            this.image = image;
        }
        public double GetReal()
        {
            return real;
        }
        public double GetImage()
        {
            return image;
        }
        public Complex Add(Complex x)
        {
            Complex temp = new Complex();
            temp.real = this.real + x.real;
            temp.image = this.image + x.image;
            return temp;
        }
        public static Complex Add(Complex x1,Complex x2)
        {
            Complex temp = new Complex();
            temp.real = x1.real + x2.real;
            temp.image = x1.image + x2.image;
            return temp;
        }
        public Complex Sub(Complex x)
        {
            Complex temp = new Complex();
            temp.real = this.real - x.real;
            temp.image = this.image - x.image;
            return temp;
        }
        public void show()
        {
            Console.WriteLine("{0}+{1}i",real,image);
        }
    }
}