I do not understand the behavior of the variables

-1

I have solved an exercise for my student career.

main ()

int cantAlumnos = 0;
int A,B,C,D,R=0;
int nota;

while (cantAlumnos < 12)
{
    cout << "Ingrese Nota: ";
    cin >> nota;
    if ((90 <= nota)&&(nota <= 100))
    {
        A++;
        cantAlumnos++;
    }
    else if ((80 <= nota)&&(nota< 90))
    {
        B++;
        cantAlumnos++;
    }
    else if ((70 <= nota)&&(nota< 80))
    {
        C++;
        cantAlumnos++;
    }
    else if ((60 <= nota)&&(nota< 70))
    {
        D++;
        cantAlumnos++;
    }
    else if ((0 <= nota)&&(nota< 60))
    {
        R++;
        cantAlumnos++;
    }
    else if ((0 > nota) || (nota > 100)) 
    {
        cout << "Nota invalida" << endl;
    }
}
cout << "Puntajes A: " << A << endl;
cout << "Puntajes B: " << B << endl;
cout << "Puntajes C: " << C << endl;
cout << "Puntajes D: " << D << endl;
cout << "Puntajes R: " << R << endl;

If the variables have been initialized in 0 , why do not they change their value after executing the while , they print random values on the screen?

Note: Example, enter 12 times 99 and return:

Ingrese Nota: 99
Ingrese Nota: 99
Ingrese Nota: 99
Ingrese Nota: 99
Ingrese Nota: 99
Ingrese Nota: 99
Ingrese Nota: 99
Ingrese Nota: 99
Ingrese Nota: 99
Ingrese Nota: 99
Ingrese Nota: 99
Ingrese Nota: 99
Puntajes A: 12
Puntajes B: 4196854
Puntajes C: -708719728
Puntajes D: 0
Puntajes R: 0
    
asked by Federico Ventura 07.05.2018 в 03:09
source

1 answer

4
  

Note: example income 12 times 99 and returns: Enter Note: 99 Enter Note: 99 Enter Note: 99 Enter Note: 99 Enter Note: 99 Enter Note: 99 Enter Note: 99 Enter Note: 99 Enter Note: 99 Enter Note: 99 Enter Note: 99 Enter Note: 99 Scores A: 12 Scores B: 4196854 Scores C: -708719728 Scores D: 0 Scores R: 0

These rare values occur because you have not initialized the variables:

//          ~ <- variable incializada
int A,B,C,D,R=0;
//  ~ ~ ~ ~   <- variables sin inicializar

The solution is as simple as initializing the variables:

int A=0, B=0, C=0, D=0, R=0;
    
answered by 07.05.2018 в 22:29