Reputation: 11
I am a newbie programmer and just started to teach myself C then decided to tackle some simple problems taken from the internet. Specifically with this one: Problem
And my solution is:
#include <stdio.h>
#include <math.h>
#include <float.h>
#include <limits.h>
int main() {
double min = DBL_MAX;
double max = DBL_MIN;
double n;
do {
scanf("%lf", &n);
if (n < 0.0001) {
break;
}
if (n > max) {
max = n;
}
if (n < min) {
min = n;
}
} while (n > 0.0000);
printf("Min: %.4f Max: %.4f\n", min, max);
return 0;
}
However, I need to run my program exactly as the input/output specified by the problem. For example, consider I am inputting in different lines:
1.1 1.2 1.3 3 6 9 11 -2 7
2.2
2.3 12
0
The program should output 12
as the max
and -2
as the min
, the program ends when the 0
was inputted.
Upvotes: 0
Views: 2233
Reputation: 21
You need to set min and max BOTH to the first value set by scanf and then check for greater and less than on later iterations. The way it works now, min starts at 0 and will never change as nothing can be lower than that without the program exiting.
int main(){
double min = 0;
double max = 0;
float n;
int count = 0;
do{
scanf("%f", &n);
if(n < 0.0001){
break;
}
if( count ) {
if(n > max){
max = n;
} else if(n < min){
min = n;
}
} else {
max = n;
min = n;
count = 1;
}
}while(n > 0);
printf("Min: %.4f Max: %.4f\n", min, max);
return 0;
}
Also, the proper type for float is %f.
Upvotes: 2
Reputation:
#include <stdio.h>
#include <math.h>
int main()
{
double min = +INFINITY;
double max = -INFINITY;
double n;
char ans = 'n';
do
{
printf("Enter a number: ");
scanf("%lf", &n);
if(n > max)
{
max = n;
}
if(n < min)
{
min = n;
}
fflush(stdin); // gets rid of previous input
printf("Another number? (y/n): ");
scanf("%c", &ans);
}
while(ans == 'y');
printf("Min: %.4f Max: %.4f\n", min, max);
return 0;
}
Output:
Enter a number: -45.6 Another number? (y/n): y Enter a number: 23.0 Another number? (y/n): y Enter a number: 92.3 Another number? (y/n): y Enter a number: -100.22 Another number? (y/n): n Min: -100.2200 Max: 92.3000 Process returned 0 (0x0) execution time : 15.805 s Press any key to continue.
Upvotes: 0
Reputation: 134
Make sure you read the problem description again, your logic in the code is tainted in comparison to what's being attempted.
According to the problem description, n
can be an int as you're using it to define the number of values to be given to the program.
You can then use a for loop (for(i=0; i < n; i++){CODE HERE}
) to gather more input from the user. The first number given should be your base value for the min
and max
values.
After you have a base value you can compare min
and max
to each input thereafter. (ie. if(max < input) {max = input}
and if(min > input) {min = input}
)
If you have anymore questions feel free to inbox me and I'll try to help you work out the problem :)
Upvotes: 0