:-/
Now, I'm trying practice on c++ basics, since few minutes I tried practice "for loop" especially, in console screen, I wrote this trivial program to calculate sin angles between angle (0 to 90) with for loop,
but when i build it, it gave me one result like my attach image, why program gave me one result..?

//sin angles from 0 to 90 | loop for
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
	double angle=0;
	double sinAngle = sin(angle);

	for (angle=0; angle<=90; angle++)
		cout << sinAngle << " " << endl;
	
	return 0;
}

Edited 6 Years Ago by iammfa: n/a

Attachments Capture02.JPG 25.14 KB

You only did the calculation once:

double angle=0;
double sinAngle = sin(angle);

This doesn't magically assign that function to sinAngle, it evaluates it at angle 0 and prints it over and over again in your loop. Leave the declaration double sinAngle; outside and move the sinAngle = sin(angle); inside your loop.

Edited 6 Years Ago by jonsca: n/a

Comments
Indeed it does :)

Step through the code to see:

int main()
{
	double angle=0;       //angle = 0
	double sinAngle = sin(angle);  //sinAngle =  0 at this point

	for (angle=0; angle<=90; angle++)  
		cout << sinAngle << " " << endl;  //sinAngle hasn't changed
	                                       //and won't change so the value ^^^
                                              //is printed 91 times
	return 0;
}

Compare with (skip the other two variables):

for (double angle=0; angle<=90; angle++)  //since you're going by 1 anyway you could use int
		cout << sin(angle) << " " << endl;  //angle is changing each 
                                                                          //pass through

P.S. the math library uses radians so you need to go from 0 to Pi/2 if you want 0-90 in degrees

Edited 6 Years Ago by jonsca: edited wrong for loop

This doesn't magically assign that function to sinAngle

Indeed it does :) - Salem

Clarification:
What I meant was that OP couldn't say double sinAngle = sin(angle); and then have the function sin(angle) (in the abstract) substitute back in for the value sinAngle down below like the OP wanted it to.

Edited 6 Years Ago by WaltP: Fixed ICODE tag

This article has been dead for over six months. Start a new discussion instead.