Variable without initializing

Asked

Viewed 506 times

4

I did a basic function of squaring (exercise of a book), and I use a variable named aux and the use to calculate the power value squared, but the compiler claims that aux is not initialized, I would like to understand why and how to solve this problem.

/*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;
}
  • 1

    How are you compiling? which compiler are you using? The variable is in use yes.

  • Hi @bigown I use Visual Studio 2015 in windows and the terminal in linux here a photo of the 'error list' of visual studio http://i.imgur.com/nr7G0Z6.png

1 answer

3


The code has an error and some redundancies (I can’t even say that you can do this account more simply x * x, I understand the experience), and I took a line to facilitate in ideone, outside 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";
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Hmmmm compriendi ok thanks =) and on the way done the book asks to do so instead of using mutiplication. thanks again.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.