Jump to content

Programming Fundamentals/Conditions/C

From Wikiversity

conditions.c

[edit | edit source]
// This program asks the user to select Fahrenheit or Celsius conversion
// and input a given temperature. Then the program converts the given 
// temperature and displays the result.
//
// References
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://en.wikibooks.org/wiki/C_Programming

#include "stdio.h"

char get_choice();
float get_temperature(char *label);
float calculate_celsius(float fahrenheit);
float calculate_fahrenheit(float celsius);
void display_result(float temperature, char *from_label, float result, char *to_label);

int main(void) {
    // main could either be an if-else structure or a switch-case structure

    char choice;
    float temperature;
    float result;

    choice = get_choice();

    // if-else approach
    if(choice == 'C' || choice == 'c') {
        temperature = get_temperature("Fahrenheit");
        result = calculate_celsius(temperature);
        display_result(temperature, "Fahrenheit", result, "Celsius");
    }
    else if(choice == 'F' || choice == 'f') {
        temperature = get_temperature("Celsius");
        result = calculate_fahrenheit(temperature);
        display_result(temperature, "Celsius", result, "Fahrenheit");
    }
    else {
        printf("You must enter C to convert to Celsius or F to convert to Fahrenheit!\n");
    }

    // switch-case approach
    switch(choice) {
        case 'C':
        case 'c':
            temperature = get_temperature("Fahrenheit");
            result = calculate_celsius(temperature);
            display_result(temperature, "Fahrenheit", result, "Celsius");
            break;
        case 'F':
        case 'f':
            temperature = get_temperature("Celsius");
            result = calculate_fahrenheit(temperature);
            display_result(temperature, "Celsius", result, "Fahrenheit");
            break;
        default:
            printf("You must enter C to convert to Celsius or F to convert to Fahrenheit!\n");
    }
    
    return 0;
}

char get_choice()
{
    char choice;
   
    printf("Enter F to convert to Fahrenheit or C to convert to Celsius: ");
    scanf(" %c", &choice);

    return choice;
}

float get_temperature(char *label) {
    float temperature;
    
    printf("Enter %s temperature: ", label);
    scanf("%f", &temperature);

    return temperature;
}

float calculate_celsius(float fahrenheit) {
    float celsius;
    
    celsius = (fahrenheit - 32) * 5 / 9;
    
    return celsius;
}

float calculate_fahrenheit(float celsius) {
    float fahrenheit;
    
    fahrenheit = celsius * 9 / 5 + 32;
    
    return fahrenheit;
}

void display_result(float temperature, char *from_label, float result, char *to_label) {
    printf("%f° %s is %f° %s", temperature, from_label, result, to_label);
}

Try It

[edit | edit source]

Copy

See Also

[edit | edit source]