Source of number_conversion.cpp


  1: //number_conversion.cpp
  2: //Illustrates the conversion of some values from one
  3: //numerical data type to another, by coercion and by casting.

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

  8: int main()
  9: {
 10:     cout << "\nThis program shows instances in which a value of one "
 11:         "data type is converted to\na value of another data type. "
 12:         "Study both source code and output very carefully.\n\n";
 13:     int i;
 14:     double r;

 16:     //Type coercion (implicit type conversion) in assignment statements:
 17:     i = 3.24;  cout << i << endl; //Each of these two lines may generate
 18:     i = 3.97;  cout << i << endl; //a conversion warning. Why?
 19:     r = 5;     cout << r << endl << endl;
 20:     //What style rule have we violated here (for the sake of readability)?

 22:     //Type coercion in arithmetic expressions:
 23:     cout << 2 * 3.51 + 4 / 1.2 << endl << endl;

 25:     //Type casting (explicit type conversion) in assignment statements:
 26:     i = static_cast<int>(3.24);  cout << i << endl;
 27:     i = static_cast<int>(3.97);  cout << i << endl;
 28:     r = static_cast<double>(5);  cout << r << endl << endl;


 31:     //Type casting is sometimes necessary in arithmetic expressions
 32:     //to obtain a correct answer, as is illustrated by:
 33:     int numberOfHits = 68;
 34:     int numberOfAtBats = 172;
 35:     double battingAverage;

 37:     battingAverage = 68 / 172;
 38:     cout << battingAverage << endl; //Gives the wrong value. Why?

 40:     battingAverage = static_cast<double>(numberOfHits / numberOfAtBats);
 41:     cout << battingAverage << endl; //Still wrong. Why?

 43:     battingAverage = static_cast<double>(numberOfHits) / numberOfAtBats;
 44:     cout << battingAverage << endl; //OK, but ...
 45:     battingAverage = static_cast<double>(numberOfHits) /
 46:                      static_cast<double>(numberOfAtBats);
 47:     cout << battingAverage << endl; //... even better (more specific)
 48:     cout << endl;


 51:     //Type casting is also useful for rounding numbers:
 52:     cout << static_cast<int>(4.37 + 0.5) << endl;
 53:     cout << static_cast<int>(4.61 + 0.5) << endl;
 54:     cout << static_cast<int>(4.37 * 10 + 0.5) / 10.0 << endl;
 55:     cout << static_cast<int>(4.61 * 10 + 0.5) / 10.0 << endl << endl;
 56: }