Program termination condition in C!

2

I have a program in C where the output should be the average of the numbers entered and how many of those values that were entered are larger than the average.

The program receives up to 100 F values, where F is a positive value between 0 and 5000 and stops receiving values when I type -1.

I'm having trouble finalizing the program, it does not end when I type -1, it only ends after I type two negative numbers.

code:

#include<stdio.h>


int contaMaiores(double vetor[], int indiceMax, double media){

  int c = 0;          // controle de indice vetor
  int m = 0;          // contador de medias

  for (c = 0; c < indiceMax; c++) {

    if (vetor[c] > media) {

      m = m + 1;

    } // fim do if

  } // fim do for

  return(m);

} // fim do contaMaiores


int main() {

  double vetor [100];                // vetor para armazenar numeros
  int contN = 0;                     // contador para numeros
  double soma = 0;
  double n;
  double media;
  int maiores;


  scanf("%lf\n", &n);

  // (1 <= N <= 100)
  // (0 <= F <= 5000)
  while (contN < 100 && n >= 0.0 && n <= 5000.0) {

    vetor[contN] = n;

    contN = contN + 1;

    soma = soma + n;

    scanf("%lf\n", &n);

  } // fim do while

  media = (soma/contN);

  maiores = contaMaiores(vetor, contN, media);

  printf("%lf\n", media);
  printf("%d\n", maiores);

  return 0;

} // fim do main
    
asked by anonymous 08.11.2018 / 05:55

2 answers

4

Dude, it's a good idea, when you ask for data entry in a repeating structure, you use a fflush(stdin) , to clear the buffer, not counting those '\ n' in scanf .

while (contN < 100 && n >= 0.0) {

    if(n <= 5000.0){
     vetor[contN] = n;

     contN = contN + 1;

     soma = soma + n;

     fflush(stdin);
     scanf("%lf", &n);

    } //Se ele inserir 6.000, não é condição de parada (-1), apenas um valor inválido.

} // fim do while
    
08.11.2018 / 09:41
3

You are doing the wrong reading. Remove the '\ n' character from your scanfs and the bug will exit.

    
08.11.2018 / 06:14