Fahrenheit and Celsius converter in Rust











up vote
4
down vote

favorite












I made a program that converts between Celsius and Fahrenheit. Is there any way that I could make this code more efficient and cleaner?



use std::io;

// C to F: F = C*(9/5) + 32
// F to C: C = (F-32)*(5/9)

/**********Converts between Fahrenheit and Celsius*********/

fn main() -> () {
println!("Do you want to convert to Celsius or Fahrenheit? Input C or F");
let mut convert_type = String::new();

io::stdin().read_line(&mut convert_type)
.expect("Failed to conversion type.");

let t = String::from(convert_type);

println!("You want to convert to: {}", t);
println!("What temperature would you like to convert?");
let mut temp = String::new();

io::stdin().read_line(&mut temp)
.expect("Failed to read temperature.");

let temp: i32 = match temp.trim().parse() {
Ok(temp) => temp,
Err(_e) => {
-1
}
};

match t.as_str() {
"Cn" => println!("{}", ftoc(temp)),
"Fn" => println!("{}", ctof(temp)),
_ => println!("t = {:?}", t),
}
}

// Celsius to Fahrenheit
fn ctof(c: i32) -> i32 {
(c * (9 / 5)) + 32

}

//Fahrenheit to Celsius
fn ftoc(f: i32) -> i32 {
(f-32) * (5 / 9)
}


Output:



    cargo run
Compiling ftoc v0.1.0 (/Users/roberthayek/rustprojects/ftoc)
Finished dev [unoptimized + debuginfo] target(s) in 2.64s
Running `target/debug/ftoc`
Do you want to convert to Celsius or Fahrenheit? Input C or F
F
You want to convert to: F

What temperature would you like to convert?
0
32









share|improve this question









New contributor




roberthayek is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 1




    Please use rustfmt the next time before pasting your code here so it fulfills the rust style guidelines which helps us reading your code.
    – hellow
    Nov 12 at 15:53















up vote
4
down vote

favorite












I made a program that converts between Celsius and Fahrenheit. Is there any way that I could make this code more efficient and cleaner?



use std::io;

// C to F: F = C*(9/5) + 32
// F to C: C = (F-32)*(5/9)

/**********Converts between Fahrenheit and Celsius*********/

fn main() -> () {
println!("Do you want to convert to Celsius or Fahrenheit? Input C or F");
let mut convert_type = String::new();

io::stdin().read_line(&mut convert_type)
.expect("Failed to conversion type.");

let t = String::from(convert_type);

println!("You want to convert to: {}", t);
println!("What temperature would you like to convert?");
let mut temp = String::new();

io::stdin().read_line(&mut temp)
.expect("Failed to read temperature.");

let temp: i32 = match temp.trim().parse() {
Ok(temp) => temp,
Err(_e) => {
-1
}
};

match t.as_str() {
"Cn" => println!("{}", ftoc(temp)),
"Fn" => println!("{}", ctof(temp)),
_ => println!("t = {:?}", t),
}
}

// Celsius to Fahrenheit
fn ctof(c: i32) -> i32 {
(c * (9 / 5)) + 32

}

//Fahrenheit to Celsius
fn ftoc(f: i32) -> i32 {
(f-32) * (5 / 9)
}


Output:



    cargo run
Compiling ftoc v0.1.0 (/Users/roberthayek/rustprojects/ftoc)
Finished dev [unoptimized + debuginfo] target(s) in 2.64s
Running `target/debug/ftoc`
Do you want to convert to Celsius or Fahrenheit? Input C or F
F
You want to convert to: F

What temperature would you like to convert?
0
32









share|improve this question









New contributor




roberthayek is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 1




    Please use rustfmt the next time before pasting your code here so it fulfills the rust style guidelines which helps us reading your code.
    – hellow
    Nov 12 at 15:53













up vote
4
down vote

favorite









up vote
4
down vote

favorite











I made a program that converts between Celsius and Fahrenheit. Is there any way that I could make this code more efficient and cleaner?



use std::io;

// C to F: F = C*(9/5) + 32
// F to C: C = (F-32)*(5/9)

/**********Converts between Fahrenheit and Celsius*********/

fn main() -> () {
println!("Do you want to convert to Celsius or Fahrenheit? Input C or F");
let mut convert_type = String::new();

io::stdin().read_line(&mut convert_type)
.expect("Failed to conversion type.");

let t = String::from(convert_type);

println!("You want to convert to: {}", t);
println!("What temperature would you like to convert?");
let mut temp = String::new();

io::stdin().read_line(&mut temp)
.expect("Failed to read temperature.");

let temp: i32 = match temp.trim().parse() {
Ok(temp) => temp,
Err(_e) => {
-1
}
};

match t.as_str() {
"Cn" => println!("{}", ftoc(temp)),
"Fn" => println!("{}", ctof(temp)),
_ => println!("t = {:?}", t),
}
}

// Celsius to Fahrenheit
fn ctof(c: i32) -> i32 {
(c * (9 / 5)) + 32

}

//Fahrenheit to Celsius
fn ftoc(f: i32) -> i32 {
(f-32) * (5 / 9)
}


Output:



    cargo run
Compiling ftoc v0.1.0 (/Users/roberthayek/rustprojects/ftoc)
Finished dev [unoptimized + debuginfo] target(s) in 2.64s
Running `target/debug/ftoc`
Do you want to convert to Celsius or Fahrenheit? Input C or F
F
You want to convert to: F

What temperature would you like to convert?
0
32









share|improve this question









New contributor




roberthayek is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











I made a program that converts between Celsius and Fahrenheit. Is there any way that I could make this code more efficient and cleaner?



use std::io;

// C to F: F = C*(9/5) + 32
// F to C: C = (F-32)*(5/9)

/**********Converts between Fahrenheit and Celsius*********/

fn main() -> () {
println!("Do you want to convert to Celsius or Fahrenheit? Input C or F");
let mut convert_type = String::new();

io::stdin().read_line(&mut convert_type)
.expect("Failed to conversion type.");

let t = String::from(convert_type);

println!("You want to convert to: {}", t);
println!("What temperature would you like to convert?");
let mut temp = String::new();

io::stdin().read_line(&mut temp)
.expect("Failed to read temperature.");

let temp: i32 = match temp.trim().parse() {
Ok(temp) => temp,
Err(_e) => {
-1
}
};

match t.as_str() {
"Cn" => println!("{}", ftoc(temp)),
"Fn" => println!("{}", ctof(temp)),
_ => println!("t = {:?}", t),
}
}

// Celsius to Fahrenheit
fn ctof(c: i32) -> i32 {
(c * (9 / 5)) + 32

}

//Fahrenheit to Celsius
fn ftoc(f: i32) -> i32 {
(f-32) * (5 / 9)
}


Output:



    cargo run
Compiling ftoc v0.1.0 (/Users/roberthayek/rustprojects/ftoc)
Finished dev [unoptimized + debuginfo] target(s) in 2.64s
Running `target/debug/ftoc`
Do you want to convert to Celsius or Fahrenheit? Input C or F
F
You want to convert to: F

What temperature would you like to convert?
0
32






rust unit-conversion






share|improve this question









New contributor




roberthayek is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




roberthayek is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited Nov 12 at 16:00









200_success

127k15148410




127k15148410






New contributor




roberthayek is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked Nov 12 at 15:38









roberthayek

212




212




New contributor




roberthayek is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





roberthayek is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






roberthayek is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








  • 1




    Please use rustfmt the next time before pasting your code here so it fulfills the rust style guidelines which helps us reading your code.
    – hellow
    Nov 12 at 15:53














  • 1




    Please use rustfmt the next time before pasting your code here so it fulfills the rust style guidelines which helps us reading your code.
    – hellow
    Nov 12 at 15:53








1




1




Please use rustfmt the next time before pasting your code here so it fulfills the rust style guidelines which helps us reading your code.
– hellow
Nov 12 at 15:53




Please use rustfmt the next time before pasting your code here so it fulfills the rust style guidelines which helps us reading your code.
– hellow
Nov 12 at 15:53










2 Answers
2






active

oldest

votes

















up vote
6
down vote













The first thing I always do is running clippy.



You will catch some things that are not neccessary, e.g.





  • fn main() -> () can be reduced to fn main()


  • let t = String::from(convert_type); is simply let t = convert_type


The bad things are





  • c * (9 / 5) which is always c because of integer arithmetic. You probably want f64::from(c) * (9.0 / 5.0)

  • same for (f - 32) * (5 / 9) should be (f64::from(f) - 32.0) * (5.0 / 9.0)) as i32


You may want to add some unit-tests to your program to verify that ctof and ftoc actually work.






share|improve this answer










New contributor




hellow is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

























    up vote
    2
    down vote













    Hellow got most of the good parts, but, I'd also recommend figuring out how you might want to signal the user so that an invalid input isn't accepted, since -1 is a temperature someone might want to convert.



    In this case I would do something like replacing



    let temp: i32 = match temp.trim().parse() {
    Ok(temp) => temp,
    Err(_e) => {
    -1
    }
    };


    with



    let temp= match temp.trim().parse() {
    Err(_e) =>{
    panic!("That wasn't valid input! Temperatures can only be integers!");
    }
    Ok(i)=>i
    };


    If I knew this program were to be used solely interactively, then I'd consider adding a loop to give the user another attempt should their input fail.






    share|improve this answer





















      Your Answer





      StackExchange.ifUsing("editor", function () {
      return StackExchange.using("mathjaxEditing", function () {
      StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
      StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
      });
      });
      }, "mathjax-editing");

      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "196"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });






      roberthayek is a new contributor. Be nice, and check out our Code of Conduct.










       

      draft saved


      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f207481%2ffahrenheit-and-celsius-converter-in-rust%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      6
      down vote













      The first thing I always do is running clippy.



      You will catch some things that are not neccessary, e.g.





      • fn main() -> () can be reduced to fn main()


      • let t = String::from(convert_type); is simply let t = convert_type


      The bad things are





      • c * (9 / 5) which is always c because of integer arithmetic. You probably want f64::from(c) * (9.0 / 5.0)

      • same for (f - 32) * (5 / 9) should be (f64::from(f) - 32.0) * (5.0 / 9.0)) as i32


      You may want to add some unit-tests to your program to verify that ctof and ftoc actually work.






      share|improve this answer










      New contributor




      hellow is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















        up vote
        6
        down vote













        The first thing I always do is running clippy.



        You will catch some things that are not neccessary, e.g.





        • fn main() -> () can be reduced to fn main()


        • let t = String::from(convert_type); is simply let t = convert_type


        The bad things are





        • c * (9 / 5) which is always c because of integer arithmetic. You probably want f64::from(c) * (9.0 / 5.0)

        • same for (f - 32) * (5 / 9) should be (f64::from(f) - 32.0) * (5.0 / 9.0)) as i32


        You may want to add some unit-tests to your program to verify that ctof and ftoc actually work.






        share|improve this answer










        New contributor




        hellow is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.




















          up vote
          6
          down vote










          up vote
          6
          down vote









          The first thing I always do is running clippy.



          You will catch some things that are not neccessary, e.g.





          • fn main() -> () can be reduced to fn main()


          • let t = String::from(convert_type); is simply let t = convert_type


          The bad things are





          • c * (9 / 5) which is always c because of integer arithmetic. You probably want f64::from(c) * (9.0 / 5.0)

          • same for (f - 32) * (5 / 9) should be (f64::from(f) - 32.0) * (5.0 / 9.0)) as i32


          You may want to add some unit-tests to your program to verify that ctof and ftoc actually work.






          share|improve this answer










          New contributor




          hellow is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          The first thing I always do is running clippy.



          You will catch some things that are not neccessary, e.g.





          • fn main() -> () can be reduced to fn main()


          • let t = String::from(convert_type); is simply let t = convert_type


          The bad things are





          • c * (9 / 5) which is always c because of integer arithmetic. You probably want f64::from(c) * (9.0 / 5.0)

          • same for (f - 32) * (5 / 9) should be (f64::from(f) - 32.0) * (5.0 / 9.0)) as i32


          You may want to add some unit-tests to your program to verify that ctof and ftoc actually work.







          share|improve this answer










          New contributor




          hellow is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          share|improve this answer



          share|improve this answer








          edited Nov 12 at 15:53





















          New contributor




          hellow is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          answered Nov 12 at 15:47









          hellow

          1615




          1615




          New contributor




          hellow is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.





          New contributor





          hellow is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.






          hellow is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.
























              up vote
              2
              down vote













              Hellow got most of the good parts, but, I'd also recommend figuring out how you might want to signal the user so that an invalid input isn't accepted, since -1 is a temperature someone might want to convert.



              In this case I would do something like replacing



              let temp: i32 = match temp.trim().parse() {
              Ok(temp) => temp,
              Err(_e) => {
              -1
              }
              };


              with



              let temp= match temp.trim().parse() {
              Err(_e) =>{
              panic!("That wasn't valid input! Temperatures can only be integers!");
              }
              Ok(i)=>i
              };


              If I knew this program were to be used solely interactively, then I'd consider adding a loop to give the user another attempt should their input fail.






              share|improve this answer

























                up vote
                2
                down vote













                Hellow got most of the good parts, but, I'd also recommend figuring out how you might want to signal the user so that an invalid input isn't accepted, since -1 is a temperature someone might want to convert.



                In this case I would do something like replacing



                let temp: i32 = match temp.trim().parse() {
                Ok(temp) => temp,
                Err(_e) => {
                -1
                }
                };


                with



                let temp= match temp.trim().parse() {
                Err(_e) =>{
                panic!("That wasn't valid input! Temperatures can only be integers!");
                }
                Ok(i)=>i
                };


                If I knew this program were to be used solely interactively, then I'd consider adding a loop to give the user another attempt should their input fail.






                share|improve this answer























                  up vote
                  2
                  down vote










                  up vote
                  2
                  down vote









                  Hellow got most of the good parts, but, I'd also recommend figuring out how you might want to signal the user so that an invalid input isn't accepted, since -1 is a temperature someone might want to convert.



                  In this case I would do something like replacing



                  let temp: i32 = match temp.trim().parse() {
                  Ok(temp) => temp,
                  Err(_e) => {
                  -1
                  }
                  };


                  with



                  let temp= match temp.trim().parse() {
                  Err(_e) =>{
                  panic!("That wasn't valid input! Temperatures can only be integers!");
                  }
                  Ok(i)=>i
                  };


                  If I knew this program were to be used solely interactively, then I'd consider adding a loop to give the user another attempt should their input fail.






                  share|improve this answer












                  Hellow got most of the good parts, but, I'd also recommend figuring out how you might want to signal the user so that an invalid input isn't accepted, since -1 is a temperature someone might want to convert.



                  In this case I would do something like replacing



                  let temp: i32 = match temp.trim().parse() {
                  Ok(temp) => temp,
                  Err(_e) => {
                  -1
                  }
                  };


                  with



                  let temp= match temp.trim().parse() {
                  Err(_e) =>{
                  panic!("That wasn't valid input! Temperatures can only be integers!");
                  }
                  Ok(i)=>i
                  };


                  If I knew this program were to be used solely interactively, then I'd consider adding a loop to give the user another attempt should their input fail.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 12 at 21:19









                  jaked122

                  13116




                  13116






















                      roberthayek is a new contributor. Be nice, and check out our Code of Conduct.










                       

                      draft saved


                      draft discarded


















                      roberthayek is a new contributor. Be nice, and check out our Code of Conduct.













                      roberthayek is a new contributor. Be nice, and check out our Code of Conduct.












                      roberthayek is a new contributor. Be nice, and check out our Code of Conduct.















                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f207481%2ffahrenheit-and-celsius-converter-in-rust%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      mysqli_query(): Empty query in /home/lucindabrummitt/public_html/blog/wp-includes/wp-db.php on line 1924

                      How to change which sound is reproduced for terminal bell?

                      Can I use Tabulator js library in my java Spring + Thymeleaf project?