Trying to set conditions and exit my loop with certain input.

Hi, I"m writing a program to acquire an amount and reject anything less than 1000. Also have to make sure program quits if 0 is the input.

double amount = 0;

cout << "mount: ";
cin >> amount;

while (true) {
if (amount < 1000) {
cout << "can't be less than 1000." << endl; break;
} if (amount != 0) {
cout << "Bye!" << endl; break;
}
}
was there a question in there?
it seems like you should modify amount in the loop somewhere?

its also convoluted -- you usurped the condition of the while to inject it into the loop body via a break. Any reason?
Last edited on
A couple of things:

1. PLEASE learn to use code tags, it makes reading and commenting on your code MUCH easier.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

HINT: You can edit your post and add code tags.

2. Post enough code to be compilable, your code snippet is not.

You were so close, your logic was just a bit "off."

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <iomanip>

int main()
{
   while (true)
   {
      std::cout << "Amount: ";
      double amount { };
      std::cin >> amount;

      if (amount < 1000)
      {
         std::cout << "Can't be less than 1000.\n\n"; continue;
      }

      std::cout << "\nYou entered: " << std::fixed << std::setprecision(2) << amount << ".\n"; break;
   }
}

Amount: 14
Can't be less than 1000.

Amount: -156
Can't be less than 1000.

Amount: 2500

You entered: 2500.00.
You should also be aware that C++ has some "fuzziness" surrounding the number of decimal digits a floating point variable can hold.

Amount: 999.9
Can't be less than 1000.

Amount: 999.9999999
Can't be less than 1000.

Amount: 999.99999999999999

You entered: 1000.00.


You should never check for equality (==) with a floating point variable.

https://stackoverflow.com/questions/10334688/how-dangerous-is-it-to-compare-floating-point-values

Hello kmoua123,

I think what you are trying to do is this:
double amount = 0;cout << "mount: ";cin >> amount;while (true){if (amount == 0){cout << "Bye!" << endl; break;}if (amount < 1000){cout <<"can't be less than 1000." << endl; break;}}
You left to much white space in your code.

Andy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

double getInput( double mn )
{
   double value;
   cout << "Enter a value >= " << mn << " (or 0 to finish): ";
   cin >> value;
   if ( value != 0 && value < mn )
   {
      cout << "Value does not lie in required range.\n";
      value = getInput( mn );
   }
   return value;
}


int main()
{
   double value = getInput( 1000.0 );
   if ( value == 0 ) return 0;
   cout << "You entered " << value << ". Now it's time to party!";
}
Thank you all for the input! It has be very helpful and I think I have it figured out now.
Topic archived. No new replies allowed.