C++ Tutorial #4 — Simple output manipulation– money

Homework: C++ Homework 2: Using external libraries to calculate numbers.

Topics covered: Manipulating the output of cout statements using the iomanip library and some of its member functions.

Source Code:

#include <iostream>
#include <iomanip>

using namespace std;   
int main(){

    double x=1.7356, y = 2.337, z=2.0, a=2.0;
    cout << setiosflags(ios::showpoint) << setprecision(3);
    cout << (x*y);
    cout << endl <<int(a*z);
     return (0);       

In this program we include a C++ library call iomanip. iomanip is a library that is used to manipulate the output of our program. We’ll talk a little bit more about the members of this below:

setiosflags is used to change the formatting of our output in some way. The way we access it is a little different from the way that we access other functions, and we’ll cover why in a later lesson. The specific members of setiosflags that we call in this program are ios::fixed and ios::showpoint. ios::fixed means that we won’t (ever) be using scientific notation on our numbers (therefore we’ll never see a number displayed as 1.06e+12 or something similar). ios::showpoint means the we will always be showing the trailing post-decimal point numbers (if there are any). The proper way to invoke these two statements are as follows:

cout << setiosflags(ios::fixed) << setiosflags(ios::showpoint);

Setprecision is a statement that specifies how many decimal points to print out after the “0”. Example if we have the number 54.271123 and used setprecision(2) it would print out: 54.27 to the console.

C++ Tutorial #3 — Order of operations, Simple interest, compounding interest
C++ Tutorial #5 — Simple if conditional, if else structure, variable output