Source of conditional_operator.cpp


  1: //conditional_operator.cpp
  2: //Illustrates use of the conditional operator ? :

  4: #include <iostream>
  5: using namespace std;

  7: int main()
  8: {
  9:     cout << "\nThis program rounds a real number temperature value to "
 10:         "an integer, chooses\nbetween a singular and a plural, and "
 11:         "chooses the maximum of two integers.\nStudy the source code "
 12:         "to see how the conditional operator ? : is used to\naccomplish "
 13:         "these amazing feats.\n";

 15:     double temp;
 16:     cout << "\nEnter a temperature value to the nearest "
 17:         "tenth of a degree: ";
 18:     cin >> temp;  cin.ignore(80, '\n');  cout << endl;
 19:     cout << "Rounded to the nearest integer, the temperature is "
 20:          << (temp >= 0  ?  int(temp+0.5)  :  int(temp-0.5)) << ".\n\n";

 22:     int numberOfTries;
 23:     cout << "Enter the number of tries you took to do something: ";
 24:     cin >> numberOfTries;  cin.ignore(80, '\n');  cout << endl;
 25:     cout << "Wow! You guessed correctly in " << numberOfTries
 26:          << (numberOfTries == 1  ?  " try.\n"  :  " tries.\n");

 28:     int i, j, max;
 29:     cout << "\nEnter two integers: ";
 30:     cin >> i >> j;  cin.ignore(80, '\n');  cout << endl;
 31:     max = (i > j  ?  i  :  j);
 32:     cout << "The larger of the two integers is " << max << ".\n";
 33:     cout << endl;
 34: }