My crash program when entering any number after 10

3

To see the error, when you ask for the number, write 10 or greater.

#include <iostream>
#include <stdlib.h>

using namespace std;

int sumalol;
int z=0;
int x;


int promedio(int digitos[])
{
int suma;

for (int i = 0; i < z;i++)
{
    suma = suma + digitos[i];
}

int prom = suma / z;

return prom;
}

int mayor()
{

}

int main()
{
int digitos[z];



cout << "Introduce la cantidad de numeros a recibir" << endl;
cin >> z;

for (int i = 0;i < z;i++)
{
        cin >> digitos[i];
}



cout << "Tus operaciones son:" << endl;
cout << "Promedio:" << promedio(digitos) << endl;
cout << "Mayor:" << endl;
cout << "Menor:" << endl;
cout << "Mediana:" << endl;
cout << "Fibonacci:" << endl;

}
    
asked by Rubén 07.10.2016 в 19:09
source

2 answers

2

The program should not even compile, since you are trying to create a dynamic array "int digits [z]". That expression does not make sense in C / C ++ if z is a variable (not const). You have to reserve dynamic memory for that array (as it has been said in other answers) in the following way:

int* digitos = new int[z];

Remember after releasing the memory:

delete[] digitos;

Another slightly more elegant way to do this would be to use a container like vector<int> that grows dynamically as you need it, but that's another story.

I have also noticed that you need to initialize the variable sum to 0 within the average function (). The final code would look like this:

#include <iostream>
#include <stdlib.h>

using namespace std;

int z = 0;

int promedio(int digitos[])
{
    int suma = 0;
    for (int i = 0; i < z; i++)
        suma = suma + digitos[i];

    return suma / z;
}

int main()
{
    cout << "Introduce la cantidad de numeros a recibir" << endl;
    cin >> z;
    int* digitos = new int[z];
    for (int i = 0; i < z; i++)
        cin >> digitos[i];

    cout << "Promedio:" << promedio(digitos) << endl;

    delete[] digitos;
}
    
answered by 11.10.2016 в 21:32
1

The problem is that you get the number of numbers to receive, z and you do not dimension your array with this value.

You must obtain the number of numbers to receive, z and with this value size your array digitos[z] :

int main()
{
//int digitos[z]; Se define pero no se dimensiona correctamente.
cout << "Introduce la cantidad de numeros a recibir" << endl;
cin >> z;
int digitos[z];  //Se dimensiona correctamente tu array.
cout << "Introduce los numeros:" << endl;
for (int i = 0;i < z;i++)
{
        //Dimensionado correctamente tu array, ahora puedes introducir los valores de 0 a z.
        cin >> digitos[i];
}
...
...
    
answered by 07.10.2016 в 19:53