본문 바로가기

Algorithm/Implementation

(Rust) - 백준(BOJ) 9297 : Reducing Improper Fractions

반응형

https://www.acmicpc.net/problem/9297

 

9297번: Reducing Improper Fractions

For each case output the line “Case x:” where x is the case number, on a single line, followed by a space, and then proper fraction. Each fraction will be of the form “I N/D”, where I is the integer part, N is the numerator of the fractional part,

www.acmicpc.net

조건에 따른 산수 결과 출력하는 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

1. test_case를 선언 후 입력받습니다.2. 이 후 for loop를 수행합니다.  2-1. 매 줄 line을 선언해 입력받습니다.  2-2. numbers vector선언 후 공백을 구분해 split, parse해 저장합니다.

📔 풀이과정

지역변수 x, y를 선언해 numbers로 부터 몫, 나머지를 구해 각각 저장합니다.

📔 정답출력

조건에 따라 정답을 출력합니다.


📕 Code

use std::io;
fn main() {
    let mut test_case = String::new();
    io::stdin().read_line(&mut test_case).expect("wrong io");
    let test_case = test_case.trim().parse::<i64>().unwrap();
    for i in 1..test_case + 1 {
        let mut line = String::new();
        io::stdin().read_line(&mut line).expect("wrong io");
        line = line.trim().to_owned();
        let numbers: Vec<i64> = line
            .split_whitespace()
            .map(|num| num.parse::<i64>().unwrap())
            .collect();
        let x = numbers[0] / numbers[1];
        let y = numbers[0] % numbers[1];
        print!("Case {}: ", i);
        if x == 0 && y != 0 {
            println!("{}/{}", y, numbers[1]);
        } else if x == 0 && y == 0 {
            println!("0");
        } else if y == 0 {
            println!("{}", x);
        } else {
            println!("{} {}/{}", x, y, numbers[1]);
        }
    }
}

📕 Test Case

input

1
0 1

Case 1: 0


*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.