What's the wrong with my code ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
POINT P[360];

	for (int i{}; i < 360; i++)
	{
		P[i].x = i;
		P[i].y = (int)sin((double)i);
	}

	CClientDC dc(this);
	RECT rc;
	GetClientRect(&rc);

	dc.SetViewportOrg(0, rc.bottom / 2);

	dc.Polyline(P, 360);


Here's my code. I want to draw the sin function. But all this draws is just a line, from (0,0) to (360, 0). No other examples please. I want to know what's the wrong with my code.

Thanks in advance.
did you check the line in large resolution? I don't see any problem in the point values.
The sin() function returns a floating point value between -1 and 1, inclusive. By casting the return to (int), you are limiting the values to -1, 0, and 1. Period. Nothing in between.

Also, the sin() function expects the parameter to be a double representing the number of radians to use. (180 degrees = PI radians, 1 degree = PI radians / 180.) You will need to multiply your loop variable "i" by PI and divide by 180:

 
P[i].x = sin((i * 3.14159) / 180);


Which means that struct POINT should be:

1
2
3
4
5
struct POINT
{
    int x;
    double y;
};


Then, to plot the graph, you will have to adjust the y-value so it varies from the top of the graph to the bottom of the graph.

OR:

You could multiply the return value from sin() by the scaling factor (y: 0 <= y <= 1; and y * scalingFactor <= half graph height.), and then cast that value to an int. Just be sure that the y-value is scaled before casting it to an integer value:

 
P[i].y = (int)(scalingFactor * sin((double)i * 3.14159 / 180.0);


(The cast of the parameter is not needed, because the compiler expects to see a double, so any numeric value, except long double, will be promoted to double automatically.)

Hope this helps...
Topic archived. No new replies allowed.