Zeus
Zeus

Reputation: 1

C++ do-While loop not looping

Here is my do-while loop

do
{
    cout << "Enter the temperature tolerance for turning on the cooling" << endl
    << "1.50 <= ToleranceCoolOn <= 6.00 (degrees Celsius)" << endl
    << "and toleranceCoolOn > toleranceHeatOff" << endl;
    cin >> tempTolCoolOn;
} 
while ( !(tempTolCoolOn < tempTolerCoolOnMax && tempTolCoolOn > tempTolerCoolOnMin) && !(tempTolCoolOn > tempTolHeatOff));

The idea is that when I type a number greater than tempTolerCoolOnMax (6.0), less than tempTolerCoolOnMin (1.5) and less than tempTolHeatOff (2.0) it should repeat the loop until I get those correct answers. However, upon typing in (6.0001) it skips the loop and proceeds to the next loop. Any ideas as to why this is happening?

Upvotes: 0

Views: 140

Answers (3)

Michael Burr
Michael Burr

Reputation: 340198

You have the spec you want right in the prompt displayed by the program - why not code it just like that?

while (! (tempTolCoolOnMin <= tempTolCoolOn && tempTolCoolOn <= tempTolerCoolOnMax && tempTolCoolOn > tempTolHeatOff))

In particular, when you have a logical/algebraic construct such as:

1.50 <= ToleranceCoolOn <= 6.00

I find it useful to code the expression as similarly as possible in C++ syntax:

1.50 <= ToleranceCoolOn && ToleranceCoolOn <= 6.00

By the way - I'm not a fan of those variable names; I find them difficult to distinguish from each other.

Upvotes: 1

anand
anand

Reputation: 11309

It should be

while ( !(tempTolCoolOn < tempTolerCoolOnMax) && !(tempTolCoolOn > tempTolerCoolOnMin) && !(tempTolCoolOn > tempTolHeatOff));

Upvotes: 0

Paul Draper
Paul Draper

Reputation: 83235

I think you want

!(tempTolCoolOn < tempTolerCoolOnMax && tempTolCoolOn > tempTolerCoolOnMin && tempTolCoolOn > tempTolHeatOff)

as the loop condition.

Upvotes: 0

Related Questions