How to reset a variable back to 0 after use in a loop in NXC

345 Views Asked by At

For some odd reason the variable "angle" will not reset back to 0 when the loop ends. All of the math is just calculating c = sqrt(a^2 + b^2 - 2abCos(theta)) the robot won't do all of the math in one line. In the full code a and b are both changing variables and are based on ultrasonic sensor input.

The sub may be called up to 3 different times and the angle variable needs to start at 0 each time the sub is called.

I have tried putting float angle = 0; or just angle = 0; in every spot imaginable but nothing works. I have even tried using int angle = 0; in multiple places.

int angle, a, b, c, csqr, theta, cosTheta, aSqrd, bSqrd, atmb, twoab;
#define pi 3.14159265359

sub calculate()  
{

 repeat(2)
 {
 float a = 172.42;
 float angle = angle + 3;
 float theta = ((angle)*(pi/180));
 float b = 172.42;
 float cosTheta = cos(theta);
 float aSqrd = pow(a, 2);
 float bSqrd = pow(b, 2);
 float atmb = (a * b);
 float twoab = (2 * atmb);
 float csqr = ((aSqrd + bSqrd) - (twoab * cosTheta));
 float c = sqrt(csqr);
 NumOut(0,0,angle);
 Wait(3000);
 ClearScreen();
 }
 float angle = 0;

}

task main()
{
     calculate();
     ClearScreen();
     calculate();
}
2

There are 2 best solutions below

1
On

Because float angle is local to the calculate method and hides the int angle in global scope. The int angle is not initialized to anything.

0
On

You have an uninitialized variable in the repeat(2) loop.

float angle = angle + 3;