|
-
February 6th, 2011, 12:32 PM
#1
Output from a for loop is incorrect due to wrong calculations.
Hey guys,
I finished the looping chapter today and have been able to solve most exercises. Now there is one exercise I need some help with.
 Originally Posted by Exercise
Write a program that calculates how much a person would earn over a period of time if his or her salary is one penny the first day and two pennies the second day, and continues to double each day. The program should ask the user for the number of days.
Display a table showing how much the salary was for each day, and then show the total pay at the end of the period. The output should be displayed in a dollar amount, not the number of pennies. Input Validation: Do not accept a number less than 1 for the number of days worked.
The issue I have is that my output with 5 days is 2 - 4 - 6 - 8 - 10 while it should be 1 - 2 - 4- 8- 10. Now I know why I am getting the first result, but I have no idea how to get the 2nd result.
Even though I tried many combinations at the part where it goes wrong, I am still not getting a correct result. I could implant several if/else if statements to counter it, but am I wrong to think it could be solved without it as well? Again, not looking for solutions, but rather a hint.
This is my code:
Code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
// Variable declaration.
int totalDays;
float total = 0;
// Input.
cout << "Pennies for Pay.\n" << endl;
cout << "Enter the number of days: ";
cin >> totalDays;
if (totalDays < 1)
{
cout << "\nError: days cannot be smaller than 0.\n" << endl;
return 0;
}
else
{
// Table creation.
cout << "\nDay(s)\tPennies" << endl;
cout << "----------------" << endl;
// Looping.
for (int day = 1; day <= totalDays; day++)
{
cout << day << "\t";
float temp = day * 2; // Calculation is wrong!
cout << temp << endl;
total += temp;
}
}
// Formatting.
cout << fixed << showpoint << setprecision(2);
// Show total.
cout << "\nTotal $: " << (total / 100) << "\n" << endl;
// End of program.
return 0;
}
lunaaaa
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|