Branching
Exercise 1 - Input Data Validation
The following program inputs a cat's age in years and converts it to a human scale age.
//**********************************************************
// Program 1 : Cat Age Conversion
// Programmer: Your Name
// Completed : 6/25/98
// Status : Complete
//
// This program calculates the age of a cat on a human scale.
//***************************************************************
#include <iostream.h>
#include <iomanip.h>
const float CAT_TO_HUMAN = 6.5; // Cat years to human years
// conversion factor
int main()
{
float catYears; // cat's age in years
float humanYears; // cat's age on human scale
// Set up floating point output format
cout.setf(ios::fixed, ios::floatfield);
cout.setf(ios::showpoint);
cout << setprecision(1);
// Get the cat's age in years
cout << "Enter cat's age in years: ";
cin >> catYears;
// Calculate the cat's age on a human scale
humanYears = CAT_TO_HUMAN * catYears;
// Print the cat's actual age and human age
cout << "If the cat actual age in years is "
<< catYears << "," << endl;
cout << "it's age in human years is "
<< humanYears << "." << endl;
return 0;
}
|
Exercise Steps:
|
Input data should be checked to verify that the input value falls into a reasonable range of values. A negative value for an age really does not make any sense. Also, most cats live less than 20 years. So an age of 33 is probably not a reasonable input value either. When an input value that is outside a reasonable range is entered, your program should not try to process that input. It should just print a message indicating what range of input values are acceptable.
|
Exercise Steps (continued): |
When you have completed this exercise, click here to check your answers.