Ok, so I have a program that basically takes over one of the basic functions of a graphinc calculator. It basically graphs a curve by taking input from the user (the amplitude, period, phase shift). Currently, with my "y" variable being a double, the program runs just fine with the following code:
for (int x = xMin; x %26lt; xMax; x++)
{
y = (2 * PI)/period * x;
y -= (2 * PI)/period * phaseAngle;
y = amplitude * cos(y);
PGraphics-%26gt;AddPoint(x, y, green);
}
The "y" variable is supposed to be an integer. If I change y to and integer, obviously I run into problems since the cos() function takes doubles, not ints. Also, I have math involving PI which definitely has a decimal in its value. I know about static_cast%26lt;double%26gt;(y) but I have no idea of how to implement this to get it to run. I tried typing this a hundred different ways and in every place possible but I still get errors... Can someone please explain to me how to get this to run using type casting?
C++ type casting? Help!?
You can either leave y as double and cast it to integer when adding the point like this:
PGraphics-%26gt;AddPoint(x, (int)y, green);
or leave it as an integer and cast the whole operation to int like this:
for (int x = xMin; x %26lt; xMax; x++)
{
y = (int)(amplitude * cos((2 * PI)/period * (x - phaseAngle));
PGraphics-%26gt;AddPoint(x, y, green);
}
If you don't need the actual real value, I preffer the second way for performance reasons.
I hope this helped you.
Reply:Keep everything as is. Just call:
PGraphics-%26gt;AddPoint( x, (int)y, green );
that should work.
bouquet
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment