Rust 练习fmt,简单算术练习


std::fmt 【详情地址】

动手实现:自定义显示:
use std::fmt;


struct List(Vec<i32>);


impl fmt::Display for List{
    fn fmt(&self,f:&mut fmt::Formatter)->fmt::Result{
        let vec = &self.0;
        let len_vec = &self.0.len();
        write!(f,"[")?;

        for (count,v) in vec.iter().enumerate(){
            if count !=len_vec-1{
                write!(f,"{}:{}",count,v)?;
                write!(f,", ")?;
            }else {
                write!(f,"{}:{}",count,v)?;
            }

        }
        write!(f,"]")
    }
}



fn main() {
    let v = List(vec![1,2,3,4,5]);
    println!("{}",v);
}
// [0:1, 1:2, 2:3, 3:4, 4:5]
use std::fmt::{self,Formatter,Display};


struct City{
    name:&'static str,
    lat:f32,
    lon:f32,
}


impl Display for City{
    fn fmt(&self,f:&mut Formatter)->fmt::Result{
        let lat_c = if self.lat >= 0.0 { 'N' } else { 'S' };
        let lon_c = if self.lon >= 0.0 { 'E' } else { 'W' };

        write!(f,"{}: {:.3}°{} {:.3}°{}",
               self.name,
               self.lat.abs(),
               lat_c,
               self.lon.abs(),
               lon_c
        )
    }
}


fn main() {
    for city in [City { name: "Dublin", lat: 53.347778, lon: -6.259722 },
                City { name: "Oslo", lat: 59.95, lon: 10.75 },
                City { name: "Vancouver", lat: 49.25, lon: -123.1 }].iter(){
        println!("{}",*city);
    }
}

动手试一试:接受一个 Matrix 作为参数,并返回一个右上 - 左下对角线上的两元素交换后的 Matrix

use std::fmt;


struct Matrix(f32,f32,f32,f32);

impl fmt::Display for Matrix{
    fn fmt(&self,f:&mut fmt::Formatter)->fmt::Result{
        write!(f,"(");
        write!(f,"{}, {}",self.0,self.1);
        write!(f,")\n");
        write!(f," (");
        write!(f,"{}, {}",self.2,self.3);
        write!(f,")")
    }
}


fn transpose(pair:(f32,f32,f32,f32))->(f32,f32,f32,f32){
    let (a,b,c,d) = pair;
    (a,c,b,d)
}

fn main() {
    let mat = Matrix(1.2,2.1,2.2,1.1);
    println!("======1=======\n {}",mat);

    // let mat_0 = (mat.0,mat.1,mat.2,mat.3);                             // struct2tuple
    let mat_tuple = transpose((mat.0,mat.1,mat.2,mat.3));
    let mat_1 = Matrix(mat_tuple.0,mat_tuple.1,mat_tuple.2,mat_tuple.3);  // tuple2struct
    println!("=======2======\n {}",mat_1);


// ======1=======
//  (1.2, 2.1)
//  (2.2, 1.1)
// =======2======
//  (1.2, 2.2)
//  (2.1, 1.1)
简单算术练习

求1000以内(不含1000)的所有被3或5整除的整数之和:

fn main() {
    // 方法一:
    let mut total = 0;
    for i in 1..1000{
        if 0 == i%3 || 0 == i%5 {
            total +=i;
        }
    }
    println!("求1000以内(不含1000)的所有被3或5整除的整数之和:{}",total);


    // 方法二:(类似于python的推导式)
    println!("求1000以内(不含1000)的所有被3或5整除的整数之和:{}",
             (1..1000)
                 .filter(|x|0 == x%3 || 0 == x%5)
                 .sum::<u32>()
    );

    // 方法三:(类似于python的推导式)
    println!("求1000以内(不含1000)的所有被3或5整除的整数之和:{}",
             (1..1000)
                 .filter(|x|0 == x%3 || 0 == x%5)
                 .fold(0,|s,a|s+a)
    );

    println!("求1000以内(不含1000)的所有被3或5整除的数集合:{:?}",
             (1..1000)
                 .filter(|x|0 == x%3 || 0 == x%5)
                 .collect::<Vec<u32>>()
    );
}

// 求1000以内(不含1000)的所有被3或5整除的整数之和:233168
// 求1000以内(不含1000)的所有被3或5整除的整数之和:233168
// 求1000以内(不含1000)的所有被3或5整除的整数之和:233168
// 求1000以内(不含1000)的所有被3或5整除的数集合:[3, 5, 6, 9, 10, 12, 15... 993, 995, 996, 999]

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 1024 设计师:白松林 返回首页