How to check if user input is a negative number and display an error message?

Asked

Viewed 1,284 times

-3

The statement says:

Write a program that reads several integer and positive numbers and calculates and shows the largest and the smallest number read. Consider that: To close the data entry, zero must be entered. For negative values, a message should be sent stating that the value is negative. Negative or zero values shall not be included in the calculations.

So far I’ve done it this way:

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

int main (void)



{


    int quant_val=0,numero=1,soma=0,maior=0,menor=0;

    printf("Insira o numero positivo: ");
    scanf("%d",&numero);

    while(numero>=1 || numero!=0){

        quant_val++;
        soma=soma+numero;



        if(numero<0){
            printf("Valor e negativo!\n");
        }

        if(numero==1){
            maior=numero;
            menor=numero;
        }

        if(numero>maior){
            maior=numero;
        }

        if(numero<menor){
            maior=numero;
        }


    printf("Insira o numero positivo: ");
    scanf("%d",&numero);

    }


    printf("O numero maior e: %d\n",maior);
    printf("O numero menor e: %d\n",menor);
    printf("A soma dos numeros e: %d\n",soma);

    system("pause");
    return 0;

}

The problem is I’m having trouble removing the negative numbers from the calculation.

Can someone help me?

  • And what happens when you enter a negative number?

  • 1

    Solved in the explanation of dear @Rovann Linhalis. Thank you!

1 answer

1


Your problem is only logic. To close the reading, the 0 soon the while is wrong:

The right thing would be:

 while(numero!=0)

And, negative number or 0, should not enter the calculation, and should display a message for negative values:

    if(numero<0){
        printf("Valor e negativo!\n");
    }
    else //Aqui está faltando!
    {

        quant_val++;
        soma=soma+numero; 

        if(numero>maior){
            maior=numero;
        }

        if(numero<menor){
            menor=numero;
        }

    }

The first assignment of higher, and lower value, do at first reading only, and not within the while:

int quant_val=0,numero=1,soma=0,maior=0,menor=0;

printf("Insira o numero positivo: ");
scanf("%d",&numero);

maior = numero;
menor = numero;

while(numero != 0)
{
    ....
}
  • 1

    Wow, well that’s right. I was cracking my head on this, thank you very much!

Browser other questions tagged

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