Temperature Converter


Program Listing

TempConverter.cpp

/************************************************************************
*                                                                       *
*   Program:    TempConverter.cpp                                       *
*                                                                       *
*   Purpose:    This program will read a temperature in either          *
*               Fahrenheit, Celsius, or Kelvin and convert it to the    *
*               equivalent temperature on all three scales.             *
*                                                                       *
************************************************************************/

#include <iostream>
#include <string>

using namespace std;

int main() {
    cout << "Enter a temperature in Fahrenheit, Celcius, or Kelvin," << endl;
    cout << "followed by F, C, K to indicate the scale (e.g., 39 F):  " << endl << endl;
    
    int temp;
    char scale;
    cin >> temp >> scale;
    
    int tempF;
    int tempC;
    int tempK;

//  Select the case based on the scale used

    switch (scale) {
    
    //  Convert Fahrenheit to Celsius and Kelvin
    
        case 'F': case 'f':
            tempF = temp;
            tempC = round(5.0/9.0*(tempF - 32));
            tempK = tempC + 273;
            break;
    
    //  Convert Celsius to Fahrenheit and Kelvin
    
        case 'C': case 'c':
            tempC = temp;
            tempF = round(9.0/5.0*tempC + 32);
            tempK = tempC + 273;
            break;
    
    //  Convert Kelvin to Fahrenheit and Celsius
    
        case 'K': case 'k':
            tempK = temp;
            tempC = tempK - 273;
            tempF = round(9.0/5.0*tempC + 32);
            break;
    
    //  Invalid input
    
        default:
            cout << "Invalid temperature scale.  Use F, C, or K" << endl;
            exit(1);
            break;
    }

//  Print the results

    cout << endl << "The temperatures are " << tempF << " F = " << tempC << " C = ";
    cout << tempK << " K" << endl;
    
    return 0;
}

Sample Run #1

Enter a temperature in Fahrenheit, Celcius, or Kelvin,
followed by F, C, K to indicate the scale (e.g., 39 F):  

32 F

The temperatures are 32 F = 0 C = 273 K

Sample Run #2

Enter a temperature in Fahrenheit, Celcius, or Kelvin,
followed by F, C, K to indicate the scale (e.g., 39 F):  

100 C

The temperatures are 212 F = 100 C = 373 K

Sample Run #3

Enter a temperature in Fahrenheit, Celcius, or Kelvin,
followed by F, C, K to indicate the scale (e.g., 39 F):  

0 K

The temperatures are -459 F = -273 C = 0 K



Return to Lectures page


e-mail me at robbk@hsc.edu

This page was last modified on Tue Dec 7 16:04:32 1999 .

URL: http://people.hsc.edu/faculty-staff/robbk/Coms261/Examples/TempConverter.html

Return to Coms 261 home page