How to display only negative values in C?

1

I have three variables:

int numero1,numero2,numero3;

Once you have declared them, I am asked the user to populate them:

        printf("Digite o primeiro numero inteiro: ");
        scanf("%d", &numero1);
        printf("Digite o segundo numero inteiro: ");
        scanf("%d",&numero2);
        printf("Digite o terceiro numero inteiro: ");
        scanf ("%d",&numero3);

And based on this, I need to check which of the numbers entered by the user are negative.

I have a method that checks whether the numbers entered are positive:

void Positivo(int valor) {
        for(count = 1;count <= valor; count++) {
            if(count > 0) {
                printf("%d \n",count);
            }
        }
    }

And I also have one that verifies that the numbers entered are negative:

void Negativo(int valor) {
    for(count = 0;count >= valor; count++) {
        if(count < 0) {
            printf("%d \n", count);
        }
    }
}

The problem is that when typing the numbers, they do not appear anything, because it seems that the negative numbers are not recognized by the function scanf() .

Screenshot of the program:

So, how can I solve this? By having the user enter negative numbers, he can read the variables correctly, and show only the negative numbers.

    
asked by anonymous 29.03.2017 / 06:36

1 answer

2

You just need to check if the number is greater or less than 0 .

void negativo_print(int a);
void positivo_print(int a);

int main(int argc, char *argv[]) {

    int a, b, c;

    puts("Digite o primeiro digito:");
    scanf("%d", &a);
    puts("Digite o segundo digito:");
    scanf("%d", &b);
    puts("Digite o terceiro digito:");
    scanf("%d", &c);

    negativo_print(a);
    negativo_print(b);
    negativo_print(c);

    return 0;
}

void negativo_print(int a){
    if(a < 0){
        printf("Numero: %d\n", a);
    }
}
void positivo_print(int a){
    if(a > 0){
        printf("Numero: %d\n", a);
    }
}

You can also use arrays:

int main(int argc, char *argv[]) {
    int n[2], i;
    size_t tmh = *(&n + 1) - n;

    puts("Digite o primeiro numero: ");
    scanf("%d", &n[0]);
    puts("\nDigite o segundo numero: ");
    scanf("%d", &n[1]);
    puts("\nDigite o terceiro numero: ");
    scanf("%d", &n[2]);

    for(i=0; i<tmh+1; i++){
        if(negativo(n[i])){
            printf("numero: %i\n", n[i]);
        }
        continue;
    }
    return 0;
}

In the for loop simply verifies whether the number is negative. If it prints on the screen, it does not jump to the next iteration if there is one.

And create a function that checks whether the number is positive or negative, zero is neutral:

int negativo(int a){
    if(a < 0) 
    {
        //negativo
        return 1;
    }
    // positvo
    return 0;
}
    
29.03.2017 / 12:20