When I am trying to get the input for my variable, it is only meeting one of the requirements (ie: the < 1
requirement) and skips the other requirement even though im using the &&
operator.
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int x;
do {
x = get_int("what is the height of the pyramid?:");
} while (x > 0 && x < 8);
printf("%i", x);
}
I tried just using the x < 8
for the requirement but it still went through when I entered 9
, 10
, 11
etc.
CodePudding user response:
If you want x
to be between 0 and 8 (both ends exclusive), then you need to repeatedly ask for input when this condition is not satisfied.
In other words, when x
is outside this range it means x
is less than or equal to 0 OR greater than or equal to 8.
That said, I believe the proper input range for that problem set is actually 1-8 (both ends inclusive):
do {
x = get_int("What is the height of the pyramid?: ")
} while (x < 1 || x > 8);
CodePudding user response:
The test is exactly the opposite of your intent. The do
/while
condition should test a condition for repeating the input and write while (!(x > 0 && x < 8));
or equivalently: while (x < 1 || x >= 8);
It is unclear what your requirements are, but it seems the number should be between 1
and 7
inclusively. If 8
should be included, the test should be modified as while (!(x > 0 && x <= 8));
or equivalently: while (x < 1 || x > 8);
do
/while
loops are often confusing and error prone. I suggest using a for(;;)
aka for ever loop and break
statements when conditions are met:
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int x;
for (;;) {
x = get_int("What is the height of the pyramid? ");
if (x == INT_MAX) {
printf("Input error or end of file\n");
return 1;
}
if (x > 0 && x < 8) {
break
}
printf("The height should be between 1 and 7\n");
}
printf("%i\n", x);
return 0;
}
CodePudding user response:
Would this work?
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int x;
do
{
x = get_int("what is the height of the pyramid?:");
}
while (x > 0 && x < 8);
{
printf("%i", x);
}
}