Problem of the Day
A new programming or logic puzzle every Mon-Fri

Temperature Conversion

W00t w00t happy Monday! Let's start off the week with a classic.

We have a lot of users from all over the world on this site. Let's help each other figure out what the weather is like. Your goal for today is to create a program that converts an integer (or double) between Fahrenheit, Celsius, and Kelvin.

Permalink: http://problemotd.com/problem/temperature-conversion/

Comments:

  • Alex - 10 years, 5 months ago

    probably not the most efficient (nor the prettiest) way of doing it but here's my attempt with JS:

    var input = "30c to k";
    
    for (var i = 0; i < input.length; i++) {
        if (input.charAt(i) == "c" || input.charAt(i) == "f" || input.charAt(i) == "k") {
            convert(input.substring(0, input.indexOf(input.charAt(i))), input.charAt(i), input.charAt(input.length - 1));
            break;
        }
    }
    
    function convert(temp, from, to) {
        switch (from) {
            case "c":
                if (to === "k") {
                    console.log(273.15 + parseInt(temp, 10));
                    break;
                } else if (to === "f") {
                    console.log(9 / 5 * parseInt(temp, 10) + 32);
                    break;
                } else {
                    console.log("can't do that");
                    break;
                }
            case "k":
                if (to === "f") {
                    console.log((parseInt(temp, 10) - 273.15) * 1.8 + 32);
                    break;
                } else if (to === "c") {
                    console.log(parseInt(temp, 10) - 273.15);
                    break;
                } else {
                    console.log("can't do that");
                    break;
                }
            case "f":
                if (to === "c") {
                    console.log(5 / 9 * (parseInt(temp, 10) - 32));
                    break;
                } else if (to === "k") {
                    console.log((parseInt(temp, 10) - 32) / 1.8 + 273.15);
                    break;
                } else {
                    console.log("can't do that");
                    break;
                }
        }
    }
    

    reply permalink

  • Mihmal - 10 years, 5 months ago

    I think that using 6 separate functions is better

    def celsius_to_kelvin(t):
      if t < -273:
        raise ArgumentError
      else: return t+273
    
    def kelvin_to_celsius(t):
      return t+273
    
    def celsius_to_fahrenheit(t):
      return t*9/5.+32
    
    def fahrenheit_to_celsius(t):
      return (t-32)*5/9. 
    
    def kelvin_to_farenheight(t):
      return (t-273.15)*1.8 + 32.00
    
    def farenheight_to_kelvin(t):
      return (t-32)*5/9. + 273.15
    

    reply permalink

Content curated by @MaxBurstein