Cast Example


CastExample.cpp

Program listing

//  Casting Example

#include <iostream>
#include <string>
#include "rational.h"

//  Function prototypes

float Max(float x, float y);        // float version of Max()

int main() {

//  Define some ints, floats, Rationals, and strings

    int i = 5;
    int j = 7;
    float f = 2.8;
    float g = 1.9;
    Rational r(8, 5);
    Rational s(13, 8);
    string str1 = "dog";
    string str2 = "cat";

//  Cast the ints as floats.  This would happen automatically.

    int bigInt = Max((float) i, (float) j);
    
//  No casting necessary

    float bigFloat = Max(f, g);

//  We can't cast Rationals as floats since there is no rule.  Instead, we use
//  the Approx() member function.  Unfortunately, the returned float will
//  be truncated when it is converted to a Rational.
    
    Rational bigRat = (Rational) Max(r.Approx(), s.Approx());

//  It is impossible to cast a string as a float.

//  string bigString = Max(str1, str2);

//  Print the results

    cout << "The larger of " << i << " and " << j << " is " << bigInt << endl;
    cout << "The larger of " << f << " and " << g << " is " << bigFloat << endl;
    cout << "The larger of " << r << " and " << s << " is " << bigRat << endl;
    
    return 0;
}

//  float Max function

float Max(float x, float y) {
    if (x > y)
        return x;
    else
        return y;
}

Sample Run

The larger of 5 and 7 is 7
The larger of 2.8 and 1.9 is 2.8
The larger of 8/5 and 13/8 is 1



Return to Lectures page


e-mail me at robbk@hsc.edu

This page was last modified on Mon Oct 18 16:34:55 1999 .

URL: http://people.hsc.edu/faculty-staff/robbk/Coms261/Examples/CastExample.html

Return to Coms 261 home page