If-else command is not working

0

In one of the exercises in a book I'm reading, I'm asked to trace a person's "profile" according to the year they were born (like those Facebook tests) but in order to limit the possibility of what is typed, I put a if to signal an error, but even with the value giving if , the else block keeps running, how can I solve?

int main(void){
    setlocale(LC_ALL,"");
    int y,a,b,c;
    printf("Digite seu ano de nascimento (quatro digitos)\n");
    scanf("%d",&y);
    if (y>9999 && y<1000) printf("Ano inválido");
        else {
        b=y%100;
        a=y/100;
        c=a+b;
        c=c%5;
        switch(c){
            case 0:printf("Tímido\n"); break;
            case 1:printf("Sonhador\n"); break;
            case 2:printf("Paquerador\n"); break;
            case 3:printf("Atraente\n"); break;
            case 4:printf("Irresistível\n"); break;
                }
            }
        return 0;
    }
    
asked by anonymous 05.04.2017 / 03:13

2 answers

1

This line

if (y>9999 && y<1000) printf("Ano inválido");

says: If Y is greater than 9999 and less than 1000 print "Invalid Year"

This condition is always false. That is, else is ALWAYS executed.

Try this:

if (y>9999 || y<1000) printf("Ano inválido");
    
05.04.2017 / 03:36
1

The comparison is using a and && when the correct would be a or || , since both are invalid. In fact it would be impossible both to be invalid because ** or ** the number is greater than 9999 or it is less than 1000, it does not have as a number to be both at the same time, which is a requirement of and .

I gave an improvement, but could improve more, could give better names to variables and even eliminate some.

#include <stdio.h>

int main(void) {
    int y = 0;
    printf("Digite seu ano de nascimento (quatro digitos)\n");
    scanf("%d", &y);
    if (y > 9999 || y < 1000) { 
        printf("Ano inválido");
    } else {
        int b = y % 100;
        int a = y / 100;
        int c = a + b;
        c %= 5;
        switch (c) {
            case 0: printf("Tímido\n"); break;
            case 1: printf("Sonhador\n"); break;
            case 2: printf("Paquerador\n"); break;
            case 3: printf("Atraente\n"); break;
            case 4: printf("Irresistível\n"); break;
        }
    }
}

See running on ideone . And on the Coding Ground. Also put it on GitHub for future reference .

    
05.04.2017 / 03:36