If else

Hello I am trying to write a program and the objective is to have the user enter in 3 numbers and then have the computer tell us which is the bigger number. Whenever I use this code it will take the numbers in but it won't tell me which one is bigger and I can't find the mistake.


#include <stdio.h>

int main ()

{
float n1, n2, n3;
printf("Enter 3 coefficients a, b, c:");
scanf("%f %f %f", &n1, &n2, &n3);

if (n1>n2)
if (n1>n3)
printf("%f is the maximum\n", n1);
else
printf("%f is the maximum\n", n3);
else if (n2>n1)
if (n2>n3)
printf("%f is the maximum\n", n2);



return 0;
}
Your if-else statements are equivalent to the following statements.

1
2
3
4
5
6
7
8
9
10
11
12
if (n1>n2)
{
   if (n1>n3)
      printf("%f is the maximum\n", n1);
   else 
      printf("%f is the maximum\n", n3);
}
else if (n2>n1)
{
   if (n2>n3)
      printf("%f is the maximum\n", n2);
}


I do not see that they produce a correct result.
Please format your post:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>

int main ()
{
    float n1, n2, n3;
    printf("Enter 3 coefficients a, b, c:");
    scanf("%f %f %f", &n1, &n2, &n3);

    if (n1>n2)
        if (n1>n3)
            printf("%f is the maximum\n", n1); //Okay
        else
            printf("%f is the maximum\n", n3); //Not true, how do you know: n3 > n2
    else if (n2>n1) //not really needed
        if (n2>n3)
            printf("%f is the maximum\n", n2); //Okay

    return 0;
}


You don't need else if in this program. Go back over the logic. Do this yourself a few time on paper, then try to model what your brain is thinking in C++.
Also, indent your code so you can follow the logic better. And, possibly consider using >= or <= in some places, instead of just > or <.
you may want also to try manipulating int data type first. its more easier to manipulate than float type.
Comparisons of floating point very often won't work that way, because they are represented as binary fractions. There are a lot of numbers that cannot be represented exactly.

This fails:

1
2
3
float a = 0.1;   // a == 0.09999997
if (10 * a == 1.0) // fails because == 0.99999997


Google C++ numeric_limits<float>epsilon

HTH
Topic archived. No new replies allowed.