Reputation: 11
Can anyone help me with this and tell me why my program keeps telling me the values are incorrect? My code runs and there are no bugs. However if I enter a high temperature of 20 and a low temperature of 10, the printf statement keeps coming up saying the value is incorrect. But it shouldn’t be because I said that if high is greater than 40 or low is less than -40 or high is greater than low! Can anyone help me? Thank you.
#define NUMS3
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int high, low;
int main(void)
{
printf("---=== IPC Temperature Analyzer ===--- \n");
for (int i = 1; i < 4; i++)
{
printf("Enter the high value for day %d:", i);
scanf("%d", &high);
printf("Enter the low value for day %d:", i);
scanf("%d", &low);
while (high > 40 || low < -40 || high < low);
{
printf("Incorrect values, temperatures must be in the range "
"-40 to 40, high must be greater than low.\n");
}
}
return 0;
}
Upvotes: 0
Views: 156
Reputation: 5207
As pointed out in the comments, because of the immediate semicolon, the while
loop has no body.
The conditions are checked and the printf()
right after the while
will always be executed. So the while
loop here as of now is useless for those values of high
and low
. But had the condition for the loop been true, it would've been an infinite loop.
And while
seems out of place there. You also need to prompt the user to re-enter correct values in case invalid values are entered.\
You could do something like
if (high > 40 || low < -40 || high < low)
{
printf("Incorrect values, temperatures must be in the range - 40 to 40, high must be greater than low.\n");
i--;
}
in place of the loop and that printf()
.
i
is decremented if invalid input is found so that at the end of the loop when i++
is done, the variable value remains the same.
Edit:
The user may enter invalid input like characters when you are expecting numbers. In such a case, scanf()
will leave the input unconsumed on the input buffer and an infinite loop can arise if that invalid data is not consumed before the scanf()
in the next iteration.
scanf()
returns the number of successful assignments.
if( scanf("%d", &high)!=1 )
{
printf("\nInvalid input.");
i--;
consumeBufferData(); //see the link
continue;
}
if( scanf("%d", &low)!=1 )
{
printf("\nInvalid input.");
i--;
consumeBufferData(); //see the link
continue;
}
If invalid input is found you should consume the invalid data. See this post to see a discussion on how to do that.
Something like
void consumeBufferData()
{
int c;
while( (c=getchar())!='\n' && c!=EOF );
}
might suffice.
Upvotes: 4