【从头写CAD】角度类(补充单元测试)

单元测试是用 #[test] 属性标记的简单函数,通常使用 assert! 或 assert_eq! 宏来检查结果。该函数仅测试时运行,运行方式是程序目录下,在命令行中敲入:cargo test。角度类补充单元测试如下

/*
* 角度弧度的类rad
** 编制人: $ource
* 修改版次及创建时间:0版完成版(2024年8月14日)
* 修改内容及时间:无
* 待完善问题:未定义梯度(grad)属性,未检查及调整rad到(-π,π)或(0,2π)范围。暂时不需要这些属性.
*/
const PI:f64=std::f64::consts::PI;
use std::ops::{Add, Sub, Mul, Div};

pub const ANGLE0:Angle=Angle{rad:0f64};
pub const ANGLE45:Angle=Angle{rad:PI/4f64};
pub const ANGLE90:Angle=Angle{rad:PI/2f64};
pub const ANGLE180:Angle=Angle{rad:PI};


#[derive(Debug,PartialEq,PartialOrd,Clone,Copy)]
pub struct Angle{
    rad:f64,
}

impl Angle{
    
    
    //构造函数(弧度) (x,y)
    pub fn new(rad:f64)->Angle{//建议调整到(-π,π)
        Angle{rad:rad}
    }
    
    pub fn from(x:f64,y:f64)->Angle{//建议调整到(-π,π)
        Angle{rad:y.atan2(x)}
    }

    //属性 弧度  角度 x  y 单位矢量
    pub fn get_radian(&self)->f64{
        self.rad
    }

    pub fn set_radian(& mut self,rad:f64)->(){
        self.rad=rad;
    }

    pub fn get_degree(&self)->f64{
        self.rad*(180f64/PI)
    }

    pub fn set_degree(&mut self,d:f64)->(){
        self.rad=d*(PI/180f64);
    }

    pub fn unit_x(&self)->f64{
        self.rad.cos()
    }

    pub fn unit_y(&self)->f64{
        self.rad.sin()
    }
}

//运算符重载 + - * /,实现加减及比例缩放
impl Add for Angle{
    type Output = Self;
    fn add(self, other: Self) ->Angle{
        Self{rad:self.rad + other.rad}
    }
}

impl Sub for Angle{
    type Output = Self;
    fn sub(self, other: Self) ->Angle{
        Self{rad:self.rad - other.rad}
    }
}

impl Mul<f64> for Angle{
    type Output = Self;
    fn mul(self, scale:f64) -> Angle {
        Angle::new(self.rad * scale)
    }
}

impl Div<f64> for Angle{
    type Output = Self;
    fn div(self, scale:f64) -> Angle {
        Angle::new(self.rad / scale)
    }
}

#[test]
fn my_test() {
    assert_eq!(ANGLE0.rad,0f64);
    assert_eq!(Angle::new(0f64),ANGLE0);
    assert_eq!(Angle::from(1f64,1f64),ANGLE45);
    assert_eq!(Angle::new(PI/2f64),ANGLE90);
    assert_eq!(Angle::new(PI),ANGLE180);
    let mut a=ANGLE0;
    a.set_degree(90f64);
    assert_eq!(a.get_radian(),PI/2f64);

    a.set_radian(PI);

    assert_eq!(a.get_degree(),180f64);

    a=Angle::from(1f64,1f64);
    assert_eq!(a.get_degree(),45f64);

    assert_eq!(a.unit_y()/a.unit_x(),1f64);
    assert_eq!(ANGLE45+ANGLE45,ANGLE180-ANGLE90);
    assert_eq!(ANGLE45*2f64,ANGLE180/2f64);
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值