Reputation: 119
I'm trying to get the max and min numbers from a contiunous scanf, but I can't seem to work it out. I get time limit exceeded. I need to do it as simple as it gets for a hw as I'm starting to learn C. Any suggestions?
#include <stdio.h>
int main(void) {
int a,b,z,f;
b=1;
while(a > -1){
scanf("%i", &a);
//printf("%i", a);
if((b>a)){
z=a;
}
if((b<a)){
f=a;
}
b=a;
}
printf("Maximum number is: %i\n", f);
printf("Minimum number is: %i", z);
}
Upvotes: 0
Views: 725
Reputation: 29126
If the end of the input is reached, a
is not converted and undefined, but itwill very likely retain its old value and the condition may never become false. scanf
returns a value: The number of items converted or the special value EOF
if the end of input has been reached. Use it.
When you first use a
, it is uninitialised and may well be negative. Your algorithm is also not correct. It doesn't find the min and max numbers, it tests how many numbers are greater than the previous number and how many are smaller with a strange result for the first number.
I'll let you work out the min/max logic by yourself, but here's a skeleton for numerical input, which stops at the end of input or at any non-numeric or negative input:
#include <stdio.h>
int main(void)
{
int a;
while (scanf("%i", &a) == 1 && a > -1) {
// process a
}
printf("Max: %i\n", amax);
printf("Min: %i\n", amin);
return 0;
}
Upvotes: 1
Reputation: 224437
You never initialize a
before the while
loop starts. Set it to 0 when you declare it.
Also, the minimum number will always be the last number you enter to break out of the loop. You probably want to do a check for that right after the scanf
.
You're also not doing a proper check against the current min and max. You should be checking a
against z
and f
, not b
, and f
and z
need to be initialized to proper starting values. And while you're at it, change z
to min
and f
to max
so they're more descriptive.
Upvotes: 2