C#简单的向量用法实例教程
程序员文章站
2024-02-21 18:42:58
本文以实例讲述了c#简单的向量用法,主要包括重载运算符>:以向量长度判断是否为真、重载运算符!=、<、<=等,具体实现代码如下:
using s...
本文以实例讲述了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 ); } }