Float Calculations


Program Listing

FloatCalcs.cpp

/****************************************************************************
*                                                                           *
*   Program:    FloatCalcs                                                  *
*                                                                           *
****************************************************************************/

#include <iostream>
#include <string>

using namespace std;

int main() {

//  Integer or floating-point division?

    float x = 50/16;
    float y = 50/17;
    
    cout << "50/16 = " << x << endl;
    cout << "50/17 = " << y << endl << endl;

//  Floating-point division

    x = 50.0/16.0;
    y = 50.0/17.0;
    
    cout << "50.0/16.0 = " << x << endl;
    cout << "50.0/17.0 = " << y << endl << endl;

//  The square root function

    x = sqrt(5.0);
    y = sqrt(-5.0);
    
    cout << "sqrt(5.0) = " << x << endl;
    cout << "sqrt(-5.0) = " << y << endl << endl;
    
//  Quadratic formula:  Solve 2x^2 + 6x + 4 = 0.

    float a = 2;
    float b = 6;
    float c = 4;
    
    float root = (-b + sqrt(b * b - 4 * a * c))/(2 * a);
    
    cout << "A root of the equation is " << root << endl;
    
    return 0;
}

Sample Run

50/16 = 3
50/17 = 2

50.0/16.0 = 3.125
50.0/17.0 = 2.94118

sqrt(5.0) = 2.23607
sqrt(-5.0) = nan

A root of the equation is -1



Return to Lectures page


e-mail me at robbk@hsc.edu

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

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

Return to Coms 261 home page