티스토리 뷰

반응형

문법이 익숙해 지도록 간단한 소스를 직접 코딩해 보고 있습니다

-------------------------------------------------------------------------------

use std::io;

use std::cmp::Ordering;

use rand::Rng;



fn main() {

 

    println!("숫자를 맞혀 봅시다.");

 

    let secret_num = rand::thread_rng().gen_range(1,5);

 

    loop {

        

        //println!("사용자가 맞혀야 할 숫자 {}", secret_num);

 

        println!("정답이라고 생각하는 숫자를 입력하세요.");

 

        let mut guess = String::new();

 

        io::stdin().read_line(&mut guess).expect("입력한 값을 읽지 못했습니다.");

 

        //println!("입력한 값 {}", guess);

 

        //let guess: u32 = guess.trim().parse().expect("입력한 값이 올바른 숫자가 아닙니다.");

 

        let guess: u32 = match guess.trim().parse() {

            Ok(num) => num,

            Err(_) => continue,

        };

 

        match guess.cmp(&secret_num) {

            Ordering::Less => println!("입력한 숫자가 작습니다."),

            Ordering::Greater => println!("입력한 숫자가 큽니다."),

            Ordering::Equal => { 

                                    println!("정답");

                                    break;

                               }

        }

    }

 

}

 

반응형