题解 | 圣诞树

圣诞树

https://www.nowcoder.com/practice/9a03096ed8ab449e9b10b0466de29eb2

use std::io;
fn main() {
    // 获取用户输入的圣诞树高度
    let mut input = String::new();
    while let Ok(_) = io::stdin().read_line(&mut input) {
    let h: usize = match input.trim().parse() { 
            Ok(num) => num,
            Err(_) => {
                break;
            }
        };

    // 初始化树枝部分
    let base = vec![
        String::from("*"),
        String::from("* *"),
        String::from("* * *"),
    ];

    // width 表示树枝的最宽的宽度
    let width = 6 * h -1;
        
    let mut tree = base.clone();
        
    for j in 1..h {
        for i in 0..3 {
            let spaces = " ".repeat(5  - 2 * i);
            tree.push(format!("{}{}{}", base[i], spaces, tree[i + 3*(j-1)]));
        }
    }
    // 输出树枝,居中对齐
    for line in &tree {
        println!("{:^width$}", line, width = width);
    }
    // 输出树干,居中对齐
    for _ in 0..h {
        println!("{:^width$}", "*", width = width);
    }
    // 清空输入缓冲区
    input.clear();
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务