elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Curso de javascript por TickTack


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación C/C++ (Moderadores: Eternal Idol, Littlehorse, K-YreX)
| | |-+  Problema con while en C
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Problema con while en C  (Leído 1,225 veces)
virtualelhacker

Desconectado Desconectado

Mensajes: 6


Ver Perfil
Problema con while en C
« 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!


« Última modificación: 4 Mayo 2014, 06:32 am por virtualelhacker » En línea

rir3760


Desconectado Desconectado

Mensajes: 1.639


Ver Perfil
Re: Problema con while en C
« Respuesta #1 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


En línea

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

Desconectado Desconectado

Mensajes: 6


Ver Perfil
Re: Problema con while en C
« Respuesta #2 en: 4 Mayo 2014, 19:12 pm »

Ahora lo veo, que amable eres! Muchas gracias!
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Problema BlueZScanner y problema de conexión
Hacking Mobile
Kasswed 3 6,327 Último mensaje 6 Mayo 2006, 22:04 pm
por Gospel
Problema Css o problema con el sidebar
Desarrollo Web
gaboomsk8 6 3,584 Último mensaje 27 Diciembre 2011, 21:56 pm
por gaboomsk8
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines