Adding step size?

Jan 26, 2016 at 2:15am
Hello Im still fairly new to C++ programming. This is my first semester using this type of coding. I am not sure how to create a step size for one of my problems for homework.

The question hints to use a for loop to step through values -2*pi to 2*pi, step size pi/10.

Last semester I used Matlab and it was easy, but C++ doesn't use the same format to creating a range. Could someone elaborate or provide an example on what to do?

Thank you in advance!
Jan 26, 2016 at 2:43am
Haven't tested this out but it should work.
1
2
3
4
5
6
7
8
constexpr double PI = 3.1415926535897;
/*
float i = -2 * PI 	: initial value
i <= 2 * PI		: condition; keep looping while this is true
i += PI/10		: how much to increment i by
*/
for(float i = -2 * PI; i <= 2 * PI; i += PI/10)
	std::cout << i << "\n";
Last edited on Jan 26, 2016 at 2:44am
Jan 26, 2016 at 3:02am
@integralfx

You really shouldn't use float or double in a for loop, I know you have used relational operators, but it's possible to go past the the limit. This is because i might be 3e-6 less than 2 * PI, causing the loop to do one more iteration. On the other hand it might do one less than you thought, because i might be 2 * PI + 3e-6, causing that iteration not to happen

Instead, work out how many times we need to loop as an int, use that value in the for loop, and increment the double in the body of the loop.

Prefer to use double rather than float, float's precision is easily exceeded.

PI/10.0 is a constexpr as well.
Jan 29, 2016 at 6:05am
@TheIdeasMan
Thanks for the constructive feedback. I'll keep this in mind when doing loops with floating point numbers. :)
Topic archived. No new replies allowed.