Please send questions to
st10@humboldt.edu .
#include <iostream>
using namespace std;
/*-------------------------------------------------
Contract: main : void -> int
Purpose: make sure that type casting in C++ works
like we think it does...
Examples: not really applicable; it performs the
given casting and prints the results
to the screen.
by: Sharon M. Tuttle
last modified: 11-3-03
----------------------------------------------------*/
int main()
{
int sumOfRolls = 595, numOfRolls = 150;
double avgRoll;
// say, for example, that you had sumOfRolls,
// an integer sum of a bunch of dice rolls.
// And, numOfRolls, an integer number of rolls.
//
// Two values that really are int's --- and which
// we might want to legitimately non-integer
// divide, to get the average roll.
// if we used integer division:
avgRoll = sumOfRolls/numOfRolls;
cout << "avg roll (using int division) is: " << avgRoll
<< endl;
// a less-klugy way: cast one of them to a double!
avgRoll = static_cast<double>(sumOfRolls)/numOfRolls;
cout << "avg roll is (using casting): " << avgRoll
<< endl;
// BUT be careful --- if cast the *result* of the
// division, you'll get integer division, and
// then simply convert the RESULTING int into
// a double...!
avgRoll = static_cast<double>(sumOfRolls/numOfRolls);
cout << "avg roll is (using wrong casting): " << avgRoll
<< endl;
// and, to deliberately convert double to int?
avgRoll = static_cast<double>(sumOfRolls)/numOfRolls;
cout << "conversion of double to int: "
<< static_cast<int>(avgRoll) << endl;
return 0;
}