C#簡略的向量用法實例教程。本站提示廣大學習愛好者:(C#簡略的向量用法實例教程)文章只能為提供參考,不一定能成為您想要的結果。以下是C#簡略的向量用法實例教程正文
本文以實例講述了C#簡略的向量用法,重要包含重載運算符>:以向量長度斷定能否為真、重載運算符!=、<、<=等,詳細完成代碼以下:
using System; class Vector { private double XVector; private double YVector; //結構函數 public Vector(double x, double y ) { XVector = x; YVector = y; } //獲得向量的長度 public double GetLength( ) { double Length = Math.Sqrt( XVector*XVector + YVector*YVector ); return Length; } //重載運算符== public static bool operator == ( Vector a, Vector b ) { return ( (a.XVector == b.XVector) && (a.YVector == b.YVector) ); } //重載運算符!= public static bool operator != ( Vector a, Vector b ) { return !( a == b ); } //重載運算符>:以向量長度斷定能否為真 public static bool operator > ( Vector a, Vector b ) { return a.GetLength( ) > b.GetLength( ); } //重載運算符< public static bool operator < ( Vector a, Vector b ) { return a.GetLength( ) < b.GetLength( ); } //重載運算符>= public static bool operator >= ( Vector a, Vector b ) { return ( a == b ) || ( a > b ); } //重載運算符<= public static bool operator <= ( Vector a, Vector b ) { return ( a == b ) || ( a < b ); } } class Test { static public void Main( ) { Vector vector1 = new Vector( 3, 4 ); Vector vector2 = new Vector( 0, 5 ); Vector vector3 = new Vector( 2, 2 ); Console.WriteLine("向量1為( 3, 4 ) \t 向量2為( 0, 5 ) \t 向量3為( 2, 2 )"); Console.WriteLine("向量1 == 向量2 為:{0}", vector1 == vector2 ); Console.WriteLine("向量1 != 向量2 為:{0}", vector1 != vector2 ); Console.WriteLine("向量1 > 向量3 為:{0}", vector1 > vector3 ); Console.WriteLine("向量2 < 向量3 為:{0}", vector2 < vector3 ); Console.WriteLine("向量1 >= 向量2 為:{0}", vector1 != vector2 ); Console.WriteLine("向量1 <= 向量2 為:{0}", vector1 != vector2 ); } }