题解 | 圣诞树

圣诞树

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

use std::io;

fn main() {
    // Read the height of the Christmas tree entered by the user
    let mut input = String::new();
    while let Ok(_) = io::stdin().read_line(&mut input) {
        if input.trim().is_empty() {
            break;
        }
        let height: usize = match input.trim().parse() { 
            Ok(h) => h,
            Err(_) => continue,
        };
        // 确保输入的数据在有效范围内
        if height < 1 || height > 100 {
            println!("Height must be between 1 and 100");
            return;
        }
    
        // 打印每组三角形,共 height 组
        for group in 1..=height {
            let max_width = (height * 3) - 1;
            // 遍历每组三角形的每一行,共 height 行
            for row in 1..=3 {
                let stars = row * group ;
                // 修正空格计算逻辑,避免下溢
                let spaces_before =  (height - group) * 3 + 3 - row;
                // 输出前导空格
                for _ in 1..=spaces_before {
                    print!(" ");
                }
                // 输出星号和中间空格
                for star_index in 1..=stars {
                    if star_index > 1 {
                        if group > 1 {
                            if row == 1 {
                                print!("    ");
                            }
                            else if row == 2 && star_index % 2 == 1 {
                                print!("  ");
                            }
                        }
                        print!(" ");
                    }
                    print!("*");
                }
                // 输出换行符
                println!();
            }
        }
    
        // 打印树干
        for _ in 0..height {
            // 打印空格,使树干居中
            for _ in 0..((height * 3) - 1) {
                print!(" ");
            }
            // 打印树干的星号
            print!("*\n");
        }
        input.clear();
    }
}

全部评论

相关推荐

qq乃乃好喝到咩噗茶:院校后面加上211标签,放大加粗,招呼语也写上211
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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