Problem with if in C my code is not working as it should
Hello get stuck in this code I can't think of how to make it work:
int main(void) {
int n1,n2;
printf("Ingrese el primer numero: ");
scanf("%d", &n1);
printf("\nIngrese el segundo numero: ");
scanf("%d", &n2);
if (n1 > n2) printf("\nEl primer numero es el mayor\n");
if (n2 < n1) printf("\nEl segundo numero es el mayor\n");
}
As you can see it's very simple but I can't find the error: c
4 answers
Very simple, both if evaluate the same condition, notice that you invert the operator and the order of the variables, thus there is no difference.
Uses instead:
if (n1 > n2) printf("\nEl primer numero es el mayor\n");
if (n2 > n1) printf("\nEl segundo numero es el mayor\n");
In your example as is, if you use a higher number first, you will see that it prints both messages.
Good cristofer, maybe I'm a little late, but there goes my answer: except for small corrections, the main problem that this code has would be in part to what md says, it is checking 2 times a condition, something that would be unnecessary, and that can bring you more than a headache like the one you have run into this code. Instead, try applying a double selective structure (if/else), there are only two results to this algorithm, so it goes as a ring to the finger.
Not only solve the main problem, but improve the performance of the algorithm by using a more appropriate structure, saving time and resources, something highly valued in the field of computer science as much as the creation of the program itself. Greetings
You can use a else
, instead of asking again. It would look like this
if (n1 > n2)
printf("\nEl primer numero es el mayor\n");
else
printf("\nEl segundo numero es el mayor\n");
Published: If you want to check if the numbers are equal you can do something like this
if (n1 > n2)
printf("\nEl primer numero es el mayor\n");
else if (n1 == n2)
printf("\nLos numeros son iguales\n");
else
printf("\nEl segundo numero es el mayor\n");
What You Missed were the brackets With this it already works for you
if(n1 > n2){printf("\nEl primer numero es el mayor\n");}
if(n2 > n1){printf("\nEl segundo numero es el mayor\n");}