Fahrenheit and Celsius converter in Rust












5














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




















  • 2




    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 '18 at 15:53
















5














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




















  • 2




    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 '18 at 15:53














5












5








5







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















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















share|improve this question













share|improve this question




share|improve this question








edited Nov 12 '18 at 16:00









200_success

128k15152414




128k15152414










asked Nov 12 '18 at 15:38









roberthayekroberthayek

263




263








  • 2




    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 '18 at 15:53














  • 2




    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 '18 at 15:53








2




2




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 '18 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 '18 at 15:53










2 Answers
2






active

oldest

votes


















9














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































    4














    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





















    • Also, if you aren't planning on using the destructured error, you might as well just use just a _ for it.
      – Arnav Borborah
      Nov 26 '18 at 11:37










    • You can write it: let temp = temp.trim().parse().expect("Your message");
      – Boiethios
      yesterday













    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',
    autoActivateHeartbeat: false,
    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
    });


    }
    });














    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









    9














    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




























      9














      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


























        9












        9








        9






        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














        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














        share|improve this answer



        share|improve this answer








        edited Nov 12 '18 at 15:53

























        answered Nov 12 '18 at 15:47









        hellowhellow

        3315




        3315

























            4














            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





















            • Also, if you aren't planning on using the destructured error, you might as well just use just a _ for it.
              – Arnav Borborah
              Nov 26 '18 at 11:37










            • You can write it: let temp = temp.trim().parse().expect("Your message");
              – Boiethios
              yesterday


















            4














            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





















            • Also, if you aren't planning on using the destructured error, you might as well just use just a _ for it.
              – Arnav Borborah
              Nov 26 '18 at 11:37










            • You can write it: let temp = temp.trim().parse().expect("Your message");
              – Boiethios
              yesterday
















            4












            4








            4






            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 '18 at 21:19









            jaked122jaked122

            15116




            15116












            • Also, if you aren't planning on using the destructured error, you might as well just use just a _ for it.
              – Arnav Borborah
              Nov 26 '18 at 11:37










            • You can write it: let temp = temp.trim().parse().expect("Your message");
              – Boiethios
              yesterday




















            • Also, if you aren't planning on using the destructured error, you might as well just use just a _ for it.
              – Arnav Borborah
              Nov 26 '18 at 11:37










            • You can write it: let temp = temp.trim().parse().expect("Your message");
              – Boiethios
              yesterday


















            Also, if you aren't planning on using the destructured error, you might as well just use just a _ for it.
            – Arnav Borborah
            Nov 26 '18 at 11:37




            Also, if you aren't planning on using the destructured error, you might as well just use just a _ for it.
            – Arnav Borborah
            Nov 26 '18 at 11:37












            You can write it: let temp = temp.trim().parse().expect("Your message");
            – Boiethios
            yesterday






            You can write it: let temp = temp.trim().parse().expect("Your message");
            – Boiethios
            yesterday




















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Code Review Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            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

            Florida Star v. B. J. F.

            Danny Elfman

            Lugert, Oklahoma