[ create a new paste ] login | about

Link: http://codepad.org/JFFuWiBL    [ raw code | output | fork ]

beebum - C++, pasted on Oct 19:
// The old 30 days program using a while loop.
// You are offered a job working in the heat from sunup to sundown for 30 days.
// Your salary starts at $0.01 per day and will double each day.
// Would you take the job? Run this program and see if the job is worth it.

#include <iostream>
#include <iomanip>
#include <string>

using std::streamsize;
using std::setprecision;

int main()
{
    double salary = .01; // daily salary
    double total = 0.0; // total of the current days salary and previous days
    const int width1 = 3; // used to format the day column
    const int width2 = 15; // used to format the salary and total columns
    streamsize prec = std::cout.precision(); // used to reset the output

    // print the column headers
    std::cout << std::endl;
    std::cout << std::setw(width1) << "Day"
              << std::setw(width2) << "Salary"
              << std::setw(width2) << "Total" << std::endl;

    // for each day, add the daily salary to the running total, print
    // the results, and then double the salary for the next day.
    int day = 1;
    while (day <= 30) {
        total += salary; // get the daily total

        // print the day, daily salary, and running total
        std::cout << std::setw(width1) << day << setprecision(12)
                  << std::setw(width2) << salary
                  << std::setw(width2) << total
                  << setprecision(prec) << std::endl;

        salary *=2; // double the salary
        ++day; // increment the day; in this case it can be ++day or day++
    }

    return 0;
}


Output:

Day         Salary          Total
  1           0.01           0.01
  2           0.02           0.03
  3           0.04           0.07
  4           0.08           0.15
  5           0.16           0.31
  6           0.32           0.63
  7           0.64           1.27
  8           1.28           2.55
  9           2.56           5.11
 10           5.12          10.23
 11          10.24          20.47
 12          20.48          40.95
 13          40.96          81.91
 14          81.92         163.83
 15         163.84         327.67
 16         327.68         655.35
 17         655.36        1310.71
 18        1310.72        2621.43
 19        2621.44        5242.87
 20        5242.88       10485.75
 21       10485.76       20971.51
 22       20971.52       41943.03
 23       41943.04       83886.07
 24       83886.08      167772.15
 25      167772.16      335544.31
 26      335544.32      671088.63
 27      671088.64     1342177.27
 28     1342177.28     2684354.55
 29     2684354.56     5368709.11
 30     5368709.12    10737418.23


Create a new paste based on this one


Comments: