Why am I getting the "0" return regardless of the entered input?

Asked

Viewed 68 times

1

#include <stdio.h>

int Comparacao(int x, int y){

    int resultado;
    if(x < y){
        resultado = -1;
    }else{
        if(x == y){
            resultado = 0;
        }else{
            resultado = 1;
        }
    }
    return resultado;
}

int main(){

    int a=0, b=0;

    puts("Digite um valor para a: ");
    scanf("%d", &a);
    puts("Digite um valor para b: ");
    scanf("%d", &b);
    Comparacao(a, b);

    return 0;
}
  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.

1 answer

2

The biggest problem is that it is not printing the result, it is being returned. Return and printing are different things. The code was discarding the result that the restornava function.

But I answered more because you can make a much simpler code:

#include <stdio.h>

int Comparacao(int x, int y)  {
    return x < y ? -1 : x != y;
}

int main(){
    int a, b;
    puts("Digite um valor para a: ");
    scanf("%d", &a);
    puts("Digite um valor para b: ");
    scanf("%d", &b);
    printf("%d", Comparacao(a, b));
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

You don’t need to use a if to perform an action. A if does not serve to compare something, it serves to perform an action conditionally, you only need a result and not an action, use the result. I preferred to use a conditional operator because it only deals with results.

I find it strange to return these values, but I won’t question the exercise. Either you misunderstood what to do. I find it more intuitive to give -1 for negative numbers, 0 for 0 and 1 for positive numbers. And there are other ways to do that, but I don’t think that’s the point of the exercise.

Nor did I need to make another conditional at the end because the result of a comparison operator is 0 if it gives false and 1 if it gives true, and it is this values that you want, so I already use the result without establishing another result.

  • If you are not familiar with the conditional operator, check: https://www.freecodecamp.org/news/c-ternary-operator/

  • I understand Maniero, very grateful for your help!

  • @Rubenfontes see the [tour], there teaches the best way to say thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.