Problema con while en C

Iniciado por virtualelhacker, 4 Mayo 2014, 06:29 AM

0 Miembros y 1 Visitante están viendo este tema.

virtualelhacker

Hola estoy empezando a programar en C y estoy con un ejercicio de calculo de promedio de unas calificaciones con while que a mi entender deberia funcionar pero no lo hace! Aqui esta mi codigo//3.8 CLASS AVERAGE PROGRAM WITH SENTINEL CONTROLLED REPETITION
#include <stdio.h>

int main (void)
{
   int counter;//number of grades entered
   int grade;//grades value
   int total;//sum of grades
   float average;//average

   //initialization phase
   total = 0;
   counter = 0;
    grade = 0;

   //processing phase
   while( grade != -1) {
       puts( "Please type the grade and press enter. To finish type \"-1\"." );//asks user to type a grade
       scanf( "%d", &grade );//stores the grade typed by the user into the grade variable
       total = total + grade;//adds the grade typed by the user to the total
       counter = counter + 1;//adds one to the counter
   }//end while

   //termination phase
   //if counter is not equal to zero, calculate the average and print it, if not print "No grades were entered"
   if( counter != 0){
       average = ( float ) total / counter;
       printf( "Average is %.2f\n", average );
   }//end if
   else{
       puts( "No grades were entered" );
   }//end else
}//end main


y aqui esta el codigo que funciona, pero me gustaría entender por que el mio no lo hace:
//3.8 CLASS AVERAGE PROGRAM WITH SENTINEL CONTROLLED REPETITION
#include <stdio.h>

int main (void)
{
   int counter;//number of grades entered
   int grade;//grades value
   int total;//sum of grades
   float average;//average

   //initialization phase
   total = 0;
   counter = 0;

   //processing phase
       puts( "Please type the grade and press enter. To finish type \"-1\"." );//asks user to type a grade
       scanf( "%d", &grade );//stores the grade typed by the user into the grade variable

   while( grade != -1) {
       total = total + grade;//adds the grade typed by the user to the total
       counter = counter + 1;//adds one to the counter
       puts( "Please type the grade and press enter. To finish type \"-1\"." );//asks user to type a grade
       scanf( "%d", &grade );//stores the grade typed by the user into the grade variable

   }//end while

   //termination phase
   //if counter is not equal to zero, calculate the average and print it, if not print "No grades were entered"
   if( counter != 0){
       average = ( float ) total / counter;
       printf( "Average is %.2f\n", average );
   }//end if
   else{
       puts( "No grades were entered" );
   }//end else
}//end main


Desde ya MUCHAS GRACIAS!

rir3760

Tu programa (el primero) no presenta los resultados correctos debido a la estructura del bucle:
while( grade != -1){ /* 4 */
   puts( "Please type the grade and press enter. To finish type \"-1\"." );
   scanf( "%d", &grade ); /* 1 */
   total = total + grade; /* 2 */
   counter = counter + 1; /* 3 */
}

Para que este termine se debe:
1) Introducir el valor -1.
2) Ese valor se agrega al total.
3) Se incrementa el contador.
4) Al inicio de la siguiente iteración se verifica la condición "!= -1" y solo entonces termina el bucle.

Espero sea evidente que el problema se debe a que el valor de salida se considera uno de los números a procesar, para evitarlo sin expresiones repetidas se debe cambiar el bucle a:
while (1){
   puts("Please type the grade and press enter. To finish type \"-1\"." );
   scanf("%d", &grade);
   
   if (grade == -1)
      break;
   
   total += grade;
   counter++;
}


Un saludo
C retains the basic philosophy that programmers know what they are doing; it only requires that they state their intentions explicitly.
--
Kernighan & Ritchie, The C programming language

virtualelhacker

Ahora lo veo, que amable eres! Muchas gracias!