Next: Example Program: Pence to Up: The Assignment statement Previous: Type Conversions

Example Program: Temperature Conversion

The following program converts an input value in degrees Fahrenheit to the corresponding value in degrees Centigrade. Note how the constant mult has been defined using an expression. A constant can be defined using an expression as long as the operands in the expression are numeric constants or the names of constants already defined. Also note that the constant has been given the value 5.0/9.0, if it had been defined by 5/9 then this would have evaluated to zero (an integer divided by an integer) which is not the intention.

// Convert Fahrenheit to Centigrade
// Enters a Fahrenheit value from the user,
// converts it to centigrade and outputs
// the result.

#include <iostream.h>

void main()
{
  const float mult = 5.0/9.0;  // 5/9 returns zero
                               // integer division
  const int sub = 32;
  float fahr, cent;
  cout << "Enter Fahrenheit temperature: ";
  cin >> fahr;
  cent = (fahr - sub) * mult;
  cout << "Centigrade equivalent of " << fahr
       << " is " << cent << endl;
}
Download program.



Next: Example Program: Pence to Up: The Assignment statement Previous: Type Conversions