I wrote the following code for a homework problem, but it's stuck in an infinate loop. I'm not sure how to correct that problem. The other issue is I want the answer to be given in two decimal places and not rounded in any way and it appears that my answers are being rounded. Any help would be greatful!

``````// this program will calculate the salary after a set number of days
// the user will input the number of days to obtain the salary
#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main()
{
// declare variables
float n = 0;
float total = 0;
float dollaramount = 0;

// prompt user for the number of days
cout << "Please enter the number of days to obtain the sum of \$0.01 per\n"
"day that doubles for the amount of days that you input:";
cin >> n;

while (n >= 1 || n <= 30)
{
total = pow(2, n) - 1;
dollaramount = total/100;

cout << "The total dollar amount will be:" << setprecision (2)
<< fixed << dollaramount << " on the " << n << " day.";

}

cout << " You entered a number outside of 1 through 30, please\n"
"start over.";

system ("pause");

return 0;
}``````
4
Contributors
4
Replies
5
Views
8 Years
Discussion Span
Last Post by sdgz747

`while (n >= 1 && n <= 30)` since the while loop runs while it's true you want it to cut out when either one of these is false. It's a bit counterintuitive at first.

To solve your other problem, I believe you need

``````float n = 0f;
float total = 0f;
float dollaramount = 0f;``````

to specify that those are float constants.

In the 'while' condition, you are not changing the 'n' value and that is why it is going in infinite loop.

for the infinite loop, while (n >= 1 || n <= 30) so -96 for example is valid because its below or equal to 30 and 5023 is also valid because it is bigger or equal to 1. Because with || (or) only one statement must be true.

to correct that, you must `do : while (n >= 1 && n <= 30)` like Jonsca said. Because any 'n' must respect both of these boundaries.

on top your 'n' value never changes...

``````while (n >= 1 || n <= 30)
{
total = pow(2, n) - 1;
dollaramount = total/100;

cout << "The total dollar amount will be:" << setprecision (2)
<< fixed << dollaramount << " on the " << n << " day.";
``````

u must enter : cin>> n; // to get a new number.

``````      }
``````