Mixed Types


Program Listing

MixedTypes.cpp

/****************************************************************************
*                                                                           *
*   Program:    MixedTypes                                                  *
*                                                                           *
****************************************************************************/

#include <iostream>
#include <string>

using namespace std;

int main() {

//  Assign float to int

    int i = 3.999;
    cout << "i = " << i << endl;
    
    i = 50.0 / 17.0;
    cout << "i = " << i << endl;

//  Assign int to float

    float x = 1234567890;
    cout << endl << "x = " << x << endl;
    
    x = 50 / 17;
    cout << "x = " << x << endl;
    
//  Assign double to float

    x = 0.333333333333;
    cout << endl << "x = " << x << endl;
    cout << "Diff = " << 0.333333333333 - x << endl;
    
//  Mixed-mode expressions - convert from Fahrenheit to Celsius

    float TempFahr;
    float TempCels;

//  Use factor of (5/9) at the beginning

    TempFahr = 50.0;
    TempCels = (5/9)*(TempFahr - 32.0);     // Fails
    cout << endl << TempFahr << " deg F = " << TempCels << " deg C" << endl;

//  Remove parentheses from 5/9 at the beginning

    TempFahr = 50.0;
    TempCels = 5/9*(TempFahr - 32.0);       // Fails
    cout << TempFahr << " deg F = " << TempCels << " deg C" << endl;

//  Put (5/9) at the end

    TempFahr = 50.0;
    TempCels = (TempFahr - 32.0)*(5/9);     // Fails
    cout << TempFahr << " deg F = " << TempCels << " deg C" << endl;

//  Remove parentheses from 5/9 at the end
    TempFahr = 50.0;
    TempCels = (TempFahr - 32.0)*5/9;       // Succeeds!
    cout << TempFahr << " deg F = " << TempCels << " deg C" << endl;

//  Chars and strings

    string s;
    string One = "One";
    string Two = "Two";

//  Add two strings

    s = One + Two;
    cout << endl << "s = " << s << endl;

//  Add a string and a char

    s = One + '2';
    cout << "s = " << s << endl;

//  Add a char and a string

    s = '1' + Two;
    cout << "s = " << s << endl;

//  Add two chars

    s = '1' + '2';
    cout << "s = " << s << endl;

    return 0;
}

Sample Run

i = 3
i = 2

x = 1.23457e+09
x = 2

x = 0.333333
Diff = -9.93444e-09

50 deg F = 0 deg C
50 deg F = 0 deg C
50 deg F = 0 deg C
50 deg F = 10 deg C

s = OneTwo
s = One2
s = 1Two
s = c



Return to Lectures page


e-mail me at robbk@hsc.edu

This page was last modified on Tue Dec 7 16:04:26 1999 .

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

Return to Coms 261 home page