简体   繁体   中英

Wrong output in printf

I'm new to C and trying to learn as best I can. I have this problem which I solved and the logic works pretty good, but whenever there is a wrong input it shows the message on screen and plus that the condition is not true. So whenever there is supposed to be an Invalid Input message I also get NE - which is what it would print out if the condition isn't true.

This is the code:

#include <stdio.h> 
#include <stdlib.h>

int main() {
    int a, b;
    scanf("%d %d", &a, &b);
    if(a <= 0 || b <= 0) {
        printf("Invalid input");
    } else {
        if(a < b) {
            int tmp = a;
            a = b;
            b = tmp;
        }
    }
    a/=10;
    int c1,c2;
    while (a!=0 && b!=0){
        c1 = a%10;
        c2 = b%10;
        a /= 100;
        b /= 10;
    }
    if (c1 == c2)
        printf("PAREN\n");
    else
        printf ("NE\n");
    return 0;
}

Its because there is nothing thats stop it to do so:

If you just want to terminate your program just return whenever if condition is true:

if(a <= 0 || b <= 0) {
printf("Invalid input");
return 1;
 } 

Alternative: Just add rest of the code under else clause.

您可以按照其他答案中的建议添加return语句,或者在第一个else子句中包含有效输入应该发生的所有事情(换句话说,只需移动第一个else子句的右括号,就在您的右括号之前main功能。)

First, let's reformat the code so it is easier to see the control flow:

int main()
{
    int a, b;
    scanf("%d %d", &a, &b);
    if(a <= 0 || b <= 0) {
        printf("Invalid input");
    } else {
        if(a < b) {
            int tmp = a;
            a = b;
            b = tmp;
        }
    }
    a/=10;
    int c1,c2;
    while (a!=0 && b!=0){
        c1 = a%10;
        c2 = b%10;
        a /= 100;
        b /= 10;
    }
    if (c1 == c2)
        printf("PAREN\n");
    else
        printf ("NE\n");
    return 0;
}

What's happening here is that when it prints "Invalid Input" the program continues running. From here it can either print "PAREN" or "NE".

I suspect what you actually want to do is to stop processing once you've determined that the input is invalid.

The simplest way to do this in your code would be to add "return 0;" immediately after the "printf("Invalid input");"line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM