Please review my code to convert temperature F > C & C > F

Practice with the concepts discussed in this chapter, try building programs to do the following: Convert temperatures between Fahrenheit and Celsius.

Helo, i was finished my chapter in the book and i'll have a task for creating this program.
Is my code have a good structure? Thanks for your feedback. I think my code is to long because i use same code for converting.

use std::io;

fn main(){

loop {

  println!("Silahkan pilih menu:");
  println!("1. Fahrenheit > Celcius");
  println!("2. Celcius > Fahrenheit");
  println!("3. Tutup program");
  println!("");
  println!("Catatan: pilih dengan memasukan angka saja.");

  let mut pilihan = String::new();

  io::stdin()
    .read_line(&mut pilihan)
    .expect("Erro, masukan angka");

  let pilihan: i32 = match pilihan.trim().parse(){
    Ok(num) => num,
    Err(_) => continue,
  };

  if pilihan ==1{

    println!("Masukan suhu dalam °C: ");
    let mut masukan = String::new();

    io::stdin()
      .read_line(&mut masukan)
      .expect("Error masukan angka");

    let masukan: i32 = match masukan.trim().parse() {
      Ok(num) => num,
      Err(_) => continue,
      };

      let fahrenheit: i32 = (masukan * 9 / 5) + 32;
      
      println!("");
      println!("{fahrenheit} °F");
      println!("");
    }

    else if pilihan ==2 {

    println!("Masukan suhu dalam °F: ");
    let mut input = String::new();

    io::stdin()
      .read_line(&mut input)
      .expect("Error masukan angka");

    let input: i32 = match input.trim().parse() {
      Ok(num) => num,
      Err(_) => continue,
      };

      let celcius: i32 = (input - 32)*5/9;
      
      println!("");
      println!("{celcius} °C");
      println!("");

    }

    else if pilihan == 3 {
      break
    }

}
}
  1. Run cargo fmt
  2. Run cargo clippy
2 Likes

The second command is works, my problem is in empty string. Thanks.

And then here's a refactored version with a couple comments clarifying what I did.

1 Like

Thank you, I really appreciate that.