/*
Basic Program File Structure and Sample Function Call
File: sum.cpp
Version: 3.1
Created: 9/24/96
Last updated: 10/20/99
Written by: Dr. C. S. Tritt
*/
#include %26lt;iostream%26gt; // Header for stream I/O.
#include %26lt;iomanip%26gt; // Header for I/O manipulators.
using namespace std;
// Function declaration (prototype) with default values.
float sum(float required_term, float optional_term = 0.0);
// Main program
int main(void)
{
// Declare variables. Some programmers like to declare their variables just
// before use. I like to declare all of mine at the top a each function.
int p; // Output numeric precision.
float a; // Units and description of a.
float b; // Units and description of b.
cout.setf(ios::showpoint); // Show decimal points. Good until explicitly changed.
cout %26lt;%26lt; "Enter the output precision (an integer): ";
cin %26gt;%26gt; p;
if (!cin)
{
cout %26lt;%26lt; "Input error. Aborting.\n";
return 1;
}
cout %26lt;%26lt; setprecision(p); // Set the precision. Good until explicitly changed.
cout %26lt;%26lt; "Enter two real numbers to be summed: ";
cin %26gt;%26gt; a %26gt;%26gt; b;
if (!cin)
{
cout %26lt;%26lt; "Input error. Aborting.\n";
return 2;
}
cout %26lt;%26lt; "Entered values: a = " %26lt;%26lt; a %26lt;%26lt; " and b = " %26lt;%26lt; b %26lt;%26lt; endl;
cout %26lt;%26lt; "So sum(a, b) = " %26lt;%26lt; sum(a, b) %26lt;%26lt; endl;
cout %26lt;%26lt; "And sum(a) = " %26lt;%26lt; sum(a) %26lt;%26lt; endl;
return 0;
}
// Define the sum function.
float sum(float x, float y)
{
// This function returns the sum of its arguments.
return (x + y);
}
this illustrates:
* Overall program structure including function declaration with default values.
* Inclusion of header files.
* Declaration of variables of built in types.
* Output formating.
* Writing to the screen (console output, i.e. cout) %26lt;%26lt; (the stream insertion operator).
* Reading from the keyboard (console in, i.e. cin) %26gt;%26gt; (the stream extraction operator).
* Simple selection structures (if statements).
* Use of functions that return values but don't change their arguments.
hawthorn
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment