LoginSignup
1
0

More than 3 years have passed since last update.

RustでAtCoder ABC169 のCを解く

Posted at

こちらを参考に有理数を用いてACした回答。

問題

依存クレート

# Cargo.toml

[dependencies]
num-rational = "=0.2.4" # 有理数サポート
text_io = "=0.1.8" # 入出力サポート

回答

use std::str::FromStr;
use num_rational::Rational64;
use text_io::read;

fn main() {
    let a: i64 = read!();
    let b: String = read!();

    // Aを有理数に変換
    let ratio_a = Rational64::new_raw(a, 1);

    // "."の前後で文字列分割する
    // 例 "1.23" => ["1", "23"]
    let bs: Vec<&str> = b.split(".").collect::<Vec<&str>>();
    let b1 = i64::from_str(bs[0]).unwrap();
    let b2 = i64::from_str(bs[1]).unwrap();

    // Bを有理数に変換
    // 例: 5.67 => 5/1 + 23/100 として計算
    let ratio_b = Rational64::new_raw(b1, 1) + Rational64::new_raw(b2, 100);

    // AとBを掛け算して出力
    let ratio_res: Rational64 = ratio_a * ratio_b;
    println!("{}", ratio_res.numer() / ratio_res.denom());
}
1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0