Variable without initializing

2

I did a basic function of squaring (exercise of a book), and I use a variable named aux and use it to compute the square power value, but the compiler claims that aux does not is initialized, I would like to understand why and how to resolve this issue.

/*fazer uma função que calcule e retorne o valor de um número ao quadrado*/

#include <stdlib.h>
#include <iostream>
using namespace std;

double square (double);

int main ()
{
    double x;
    cout << "Digite um numero:\n";
    cin >> x;

    system ("clear");

    cout << "O numero " << x << " elevado ao quadrado eh: " << square (x) << "\n";
}

double square (double x)
{
    int i;
    double aux;

    for (i = 0; i < x; i++)
    {
        aux = aux + x;
    }

    return aux;
}
    
asked by anonymous 14.01.2016 / 17:21

1 answer

2

The code has an error and some redundancies (I do not say that I can do this account in a simpler way x * x , I understand the experience), and I drew a line to facilitate in the ideone, otherwise this is not to give error:

#include <iostream>
using namespace std;

double square(double x) {
    double aux = 0; // <=========== tinha que inicializar a variável aqui
    for (int i = 0; i < x; i++) {
        aux += x;
    }
    return aux;
}
int main() {
    double x;
    cout << "Digite um numero:\n";
    cin >> x;
    cout << "O numero " << x << " elevado ao quadrado eh: " << square(x) << "\n";
}

See running on ideone .

    
14.01.2016 / 17:29