Reputation: 33
I'm taking a C programming class this semester and I have absolutely no programming experience, this is making it extremely difficult for me to do the assignments or even study.
the assignment is to write a program that will allow the user to input any amount of values and display the largest and smallest values that were inputted.
it has to accept positive and negative number and entering 0 will terminate the program.
if the first number entered is 0 then a message stating this must be displayed.
this may be quite laughable to some of you, but here is what I have.
#include <stdio.h>
int main(void)
{
float max=0, a;
float min=0, b;
printf("Entering 0 will terminate the sequence of input values.\n");
do{ printf("Enter Number:");
if (scanf(" %f", &a)==1);{
if(a<max){
a=max;}
if(a>min){
a=min;}
}
} while(a!=0);
printf("Your largest number was %.3f. Your smallest number was %.3f.", max, min);
return 0;
}
also, can any of you recommend and reference materials that will help me learn this stuff, thank you.
Upvotes: 2
Views: 36572
Reputation: 18737
Try this:
while(1)
{
printf("Enter Number:");
if (scanf("%f", &a)==1)
{
if(a==0) //check if the input value is 0 then break the loop
break;
else
{
if(a>max)
max=a;
if(a<min)
min=a;
}
}
else
break;
}
If entered value is greater than max, then max is replaced by that number. And if a is less than min, then min is replaced by that number.
Upvotes: 1
Reputation: 50657
It should work if you fix the following issues.
You need to change
if (scanf(" %f", &a)==1);{
^ ^
to
if (scanf("%f", &a)==1){
For
while(a!=0);
^^^
It's a bad practice to compare float
using !=
. Better to use the following instead
while(fabs(a) > 0.001);
.
As commented by @JonathanLeffler, actually it will be OK for this case. But in general, you certainly need to be careful about whether it is appropriate to compare two floating point values for equality, especially after a computation
Your logic is wrong, you should update max/min
instead of a
. So change
if(a > max) {
a = max;
}
if(a < min) {
a = min;
}
to
if ( fabs(a) < 0.001 ) // if a~0, stop evaluating
//, otherwise, you will always get 0 as the min
break;
if(a > max) {
max = a;
}
if(a < min) {
min = a;
}
You should initialize min
to be a very large number (e.g. FLT_MAX
) at first to make it able to update based on a < min
. And you'd better set float max=FLT_MIN
if you want to handle negative numbers.
See it live: http://ideone.com/XQYkeD.
Upvotes: 2