-
Rust연습_Create a Calculator App러스트로 계산기 만들기-Engineer man코딩Coding/Rust연습 2021. 5. 11. 23:12728x90
use std::io::{stdin, stdout, Write}; fn read(input: &mut String) { stdout().flush().expect("failed to flush"); stdin().read_line(input).expect("failed to read"); } fn main() { println!("Welcome to engineer man's calculator!"); println!("--------------------"); let mut num1 = String::new(); let mut num2 = String::new(); let mut operator = String::new(); println!("What is the first number?: "); read(&mut num1); println!("What is the sencond number?: "); read(&mut num2); println!("What operation would you like to do? [+-*/]: "); read(&mut operator); let num1: f32 = num1.trim().parse().unwrap(); let num2: f32 = num2.trim().parse().unwrap(); let operator: char = operator.trim().chars().next().unwrap(); let operators = String::from("+-*/"); if !operators.contains(operator) { println!("unknown operator"); return; } let result = match operator { '+' => num1 + num2, '-' => num1 - num2, '*' => num1 * num2, '/' => num1 / num2, _ => panic!("error in operator"), }; println!("the result of {} {} {} = {}", num1, operator, num2, result); }
결과
출처
https://youtu.be/RYTMn_kLItw
12345678910111213141516171819202122232425262728293031323334353637383940414243444546use std::io::{stdin, stdout, Write};fn read(input: &mut String) {stdout().flush().expect("failed to flush");stdin().read_line(input).expect("failed to read");}fn main() {println!("Welcome to engineer man's calculator!");println!("--------------------");let mut num1 = String::new();let mut num2 = String::new();let mut operator = String::new();println!("What is the first number?: ");read(&mut num1);println!("What is the sencond number?: ");read(&mut num2);println!("What operation would you like to do? [+-*/]: ");read(&mut operator);let num1: f32 = num1.trim().parse().unwrap();let num2: f32 = num2.trim().parse().unwrap();let operator: char = operator.trim().chars().next().unwrap();let operators = String::from("+-*/");if !operators.contains(operator) {println!("unknown operator");return;}let result = match operator {'+' => num1 + num2,'-' => num1 - num2,'*' => num1 * num2,'/' => num1 / num2,_ => panic!("error in operator"),};println!("the result of {} {} {} = {}", num1, operator, num2, result);}cs 반응형'코딩Coding > Rust연습' 카테고리의 다른 글
Rust연습]Common Programming Concepts in Rust (0) 2021.12.06 Rust연습) Guessing Game in Rust (0) 2021.12.04 Rust연습_Fibonacci피보나치 출력 (0) 2021.05.13 Rust연습_피보나치 수열 출력하기 (0) 2021.05.13 Rust연습 - 구조체 및 열거형을 사용하여 코드 수정(exercise-structs-enums) (0) 2021.05.11 Rust연습_추리 게임 튜토리얼 (0) 2021.05.09 Rust연습_Booleans-bool 형식 (0) 2021.05.08 Rust연습_문자 및 문자열출력Character and strings (0) 2021.05.08