Foro de elhacker.net

Programación => Programación C/C++ => Mensaje iniciado por: virtualelhacker en 4 Mayo 2014, 06:29 am



Título: Problema con while en C
Publicado por: virtualelhacker en 4 Mayo 2014, 06:29 am
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
Código:
//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:
Código:
//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!


Título: Re: Problema con while en C
Publicado por: rir3760 en 4 Mayo 2014, 06:56 am
Tu programa (el primero) no presenta los resultados correctos debido a la estructura del bucle:
Código
  1. while( grade != -1){ /* 4 */
  2.   puts( "Please type the grade and press enter. To finish type \"-1\"." );
  3.   scanf( "%d", &grade ); /* 1 */
  4.   total = total + grade; /* 2 */
  5.   counter = counter + 1; /* 3 */
  6. }
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:
Código
  1. while (1){
  2.   puts("Please type the grade and press enter. To finish type \"-1\"." );
  3.   scanf("%d", &grade);
  4.  
  5.   if (grade == -1)
  6.      break;
  7.  
  8.   total += grade;
  9.   counter++;
  10. }

Un saludo


Título: Re: Problema con while en C
Publicado por: virtualelhacker en 4 Mayo 2014, 19:12 pm
Ahora lo veo, que amable eres! Muchas gracias!