Converting Celsius to Fahrenheit round-up

July 22, 2024
0 comments Go, Node, Python, Bun, Ruby, Rust, JavaScript

In the last couple of days, I've created variations of a simple algorithm to demonstrate how Celcius and Fahrenheit seem to relate to each other if you "mirror the number".
It wasn't supposed to be about the programming language. Still, I used Python in the first one and I noticed that since the code is simple, it could be fun to write variants of it in other languages.

  1. Converting Celsius to Fahrenheit with Python
  2. Converting Celsius to Fahrenheit with TypeScript
  3. Converting Celsius to Fahrenheit with Go
  4. Converting Celsius to Fahrenheit with Ruby
  5. Converting Celsius to Fahrenheit with Crystal
  6. Converting Celsius to Fahrenheit with Rust

It was a fun exercise.

Truncated! Read the rest by clicking the link below.

Converting Celsius to Fahrenheit with Rust

July 20, 2024
0 comments Rust

Previously in this series:

  1. Converting Celsius to Fahrenheit with Python
  2. TypeScript
  3. Go
  4. Ruby
  5. Crystal

This time, in Rust:


fn c2f(c: i8) -> f32 {
    let c = c as f32;
    c * 9.0 / 5.0 + 32.0
}

fn is_mirror(a: i8, b: i8) -> bool {
    let a = massage(a);
    let b = reverse_string(massage(b));
    a == b
}

fn massage(n: i8) -> String {
    if n < 10 {
        return format!("0{}", n);
    } else if n >= 100 {
        return massage(n - 100);
    } else {
        return format!("{}", n);
    }
}

fn reverse_string(s: String) -> String {
    s.chars().rev().collect()
}

fn print_conversion(c: i8, f: i8) {
    println!("{}°C ~= {}°F", c, f);
}

fn main() {
    let mut c = 4;
    while c < 100 {
        let f = c2f(c);
        if is_mirror(c, f.ceil() as i8) {
            print_conversion(c, f.ceil() as i8)
        } else if is_mirror(c, f.floor() as i8) {
            print_conversion(c, f.floor() as i8)
        } else {
            break;
        }
        c += 12;
    }
}

Run it like this:


rustc -o conversion-rs conversion.rs && ./conversion-rs

and the output becomes:

4°C ~= 40°F
16°C ~= 61°F
28°C ~= 82°F
40°C ~= 104°F
52°C ~= 125°F
Previous page
Next page