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

-3

The statement says:

  

Write a program that reads multiple integers and positives and calculates and shows the largest and smallest numbers read. Consider that:   To terminate data entry, zero must be entered.   For negative values, a message should be sent stating that the value is negative.   Negative or zero values will not be entered in the calculations.

So far I have done the following:

#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 that I can not remove the negative numbers from the calculation.

Can anyone help me?

    
asked by anonymous 18.12.2017 / 00:42

1 answer

1

Your problem is just logical. To close the reading, you must enter the 0 logo while the while is wrong:

The correct one would be:

 while(numero!=0)

And, negative numbers 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 greatest, and least value, does at first reading only, and not within 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)
{
    ....
}
    
18.12.2017 / 00:50