Tuesday, January 3, 2017

Programming Challenge 6.7 - Celsius Temperature Table

/* Celsius Temperature Table - The formula for converting a temperature
   from Fahrenheit to Celsius is:

   * C = 5/9 (F-32)

   Where F is the Fahrenheit temperature and C is the Celsius temperature.

   This program uses the following function:

   * celsius()

   The function is demonstrated by calling it in a loop that displays a
   table of the Fahrenheit temperatures 0 through 20 and their Celsius
   equivalents. */

#include "Utility.h"

/* Prototype: Celsius */
double celsius (double);

int main()
{
   /* Variable: Fahrenheit */
   double tempFahrenheit = 0.0,
          tempCelsius = 0.0;

   /* Set Up: Numeric output formatting */
   cout << fixed << showpoint << setprecision(1);

   /* Display: Introduction */
   cout << "\t\tCelsius Temperature Table - Function Demo\n\n"
        << "This program converts a range of temperatures in degree\n"
        << "Fahrenheit to degree Celsius with a custom function,\n"
        << "which is demonstrated here.\n\n";

   /* Display: Table header */
   cout << "Temperature Fahrenheit:" << "\t\t"
        << "Temperature Celsius:\n"
        << "----------------------\t\t-------------------\n";

   /* This loop calls celsius, which converts fahrenheit to
      celsius, which is returned and stored in the variable
      tempCelsius, then displays the result of the conversion
      process */
   while (tempFahrenheit <= 20)
   {
      tempCelsius = celsius(tempFahrenheit);

      cout << setw(6) << left << tempFahrenheit
           << "\t\t\t\t"
           << setw(4) << right << tempCelsius << endl;

      tempFahrenheit++;
   }

   pauseSystem();
   return 0;
}

/* **********************************************************
   Definition: celsius

   This function accepts a Fahrenheit temperature as an
   argument, and returns the temperature, converted to
   Celsius.
   ********************************************************** */

double celsius(double fToCelsius)
{
   /* Calculation: fToCelsius gets the fahrenheit temperature
      from tempFahrenheit as argument, then converts it to °C
      by way of the formula °C = (F - 32) / 1.8 (where 1.8 is
      the fraction 9/5 converted to decimal) */
      fToCelsius = (fToCelsius - 32) / 1.8;

   /* Return: The celsius temperature to tempCelsius in main */
   return fToCelsius;
}

No comments:

Post a Comment