Search code examples
c++cmath

C++ giving a negative number when I square


So I have some code that is supposed to be giving me the points on a parabola but the problem is that when I square the number when it is a negative it gives me a negative back which wont work.

#include "TileClass.h"
//#include <cmath> included in other header
// Original equation y=-x^2+4


void Tile::Loc() {
    for (int a = -2; a < 3; a = a + 1) {
        cout << "--- " << a << endl;
        cout << "Pw" << (a << 2) << endl;
        cout << ((a << 2) + 4) << endl;
    }

}

output

--- -2
Pw-8
-4
--- -1
Pw-4
0
--- 0
Pw0
4
--- 1
Pw4
8
--- 2
Pw8
12


Solution

  • The C++ operator << is not the square operator. It is the bitshift operator.

    Try

    -(a*a)+4
    

    instead