Negative, positive and zero numbers do not return as expected

Asked

Viewed 160 times

0

The code is ignoring the type variable int and is receiving real values.

Also, when I enter a character it returns that is zero and not that it is not a valid number.

Identify whether it is positive, negative or zero works.

int main(void){
    int Num;

    printf("Digite um numero inteiro: ");
    scanf("%f", &Num);

    if(Num > 0){
        printf("O numero e positivo");
    }else if(Num < 0){
        printf("O numero e negativo");
    }else if(Num == 0){
        printf("O numero e zero");
    }else{
        printf("Nao e um numero valido");
    }
}
  • 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 for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

1

If you are programming in C (the question is C++), you should use the input formatter %d. but even not doing this is not to give any problem in any compiler (some will prevent compiling, but if compiling it will still take the whole part of typing). I took out the unnecessary parts of the code and formatted it better. I didn’t make any major validations, if something invalid is typed it won’t fall into else how are you finding (see more):

int main(void) {
    int num;
    printf("Digite um numero inteiro: ");
    scanf("%d", &num);
    if (num > 0) printf("O numero e positivo");
    else if (num < 0) printf("O numero e negativo");
    else if (num == 0) printf("O numero e zero");
}

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

If you are using C++ even suggest then use cin and cout and you won’t have these problems.

  • I saw one of the mistakes I made, I put the variable to whole type, and in the input of the data I put the type float. However the problem still continues, if I type for example 9,43243, it returns which is positive, and was not to return, because this is not an integer. And if I type "abc" it returns zero, I think languages like Vb.net understand that that is not a valid number, but in C++ do not

  • In this case read the line and do all the checks you think necessary in the read string and if they are satisfied all do the desired conversion.

  • @Gabrielfratuccidosreis I answered what you asked and showed you that you need to do validation if you are typing the data correctly, and even not asking I passed up a link for you to see that you have how to know if the data is valid, now you can put in your code the check if you need it, since you will insist on doing C in C++.

Browser other questions tagged

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