Program completion condition in C!

Asked

Viewed 134 times

2

I have a program in C where the output should be the average of the numbers typed and how many of these values were typed 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 finishing the program, it doesn’t finish 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

2 answers

4

Dude, it’s a good thing, when you ask for data entry into a repeat structure, you use a fflush(stdin), to clean the buffer, without taking into account these ' n' no 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

3

You are reading incorrectly. Remove the ' n' character from your scanfs and the bug will come out.

Browser other questions tagged

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