That happened because you didn't change the value of variable (userNum)
within the loop..
you should use do..while instead
1 2 3 4 5 6 7 8 9 10 11 12 13
do
{
cout << "Please enter a number between 3 and 99: ";
cin >> userNum;
if (userNum < 3 || userNum > 99)
{
cout << "Please follow the directions!" << endl;
}
} while (userNum < 3 || userNum > 99) ;
It's running well until I try to see if it work for a number that is not divisible by 3. For example, I put in the number 17, I get:
"Please enter a number 3 and 99: 17
17 is multiple number 5 of 3.
Press any key to continue . . ."
It shouldn't say it is a multiple, but it is "not" a multiple.
Here is my code:
[code]
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
int main(){
int num = 0;
int f = 0;
int count = 0;
cout << "Please enter a number 3 and 99: ";
cin >> num;
f=(num/3);
if(num>=3 && num<=99)
{
cout << num << " is multiple number " << f << " of 3." << endl;
count++;
}
else if (count>0 && (num%3)==0)
{
cout << num << " is not a multiple of 3.";
}
else{
cout << "Please follow the directions";
}
@Arslan It is set up as a loop. It means exactly what it says. "Run this loop as long as userName is lower than 3 OR higher than 99." e.g 1,2, 150, 544 etc.
@Arslan It is set up as a loop. It means exactly what it says. "Run this loop as long as userName is lower than 3 OR higher than 99." e.g 1,2, 150, 544 etc.
So what the difference between that and an if-statement. Wouldnt an if-statement have done the same thing?
It would have done exactly the same but only once. In the original code by the OP, the while loop is used in a wrong way. It should be like this -
1 2 3
while (userNum < 3 || userNum > 99){
cout << "Please follow the directions!" << endl;
cin >> userNum;
And it should be a do-while loop. Either way, what Im trying to say is.
if we used an if statement, we would just check if userNum was between 3 and 99 ONCE.
if we used a loop like the code I just showed above, then what is in the loop will keep getting checked until userNum IS between 3 and 99. And as long as the user keeps inputing a number that is less than 3 and more than 99, it will keep telling him to please follow directions.