Looking for a better way to write this code...


I have this piece of code that I think may be improved but I can't think of a good way of going about it. Hoping someone understands and can help me.
Below is an example of it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

// The goal is increment CurrPosition with Velocity, however, CurrPosition must remain an int.
int main()
{
	int 	CurrPosition = 0,		// Current Position
		IncAmt;				// Update difference, may be 0
	float 	Velocity = 0.27f,		// Amount of update per iteration
		DiffBetweenSteps = 0;	// 'hold over' amount after getting an integer step

	while( CurrPosition < 10 )
	{
		// --------- Looking for improvements here --------
		// Increment difference
		DiffBetweenSteps += Velocity

		// Only get the integer amount of update
		IncAmt	= static_cast<int>(DiffBetweenSteps);

		// Remove this amount to get the float difference between steps
		DiffBetweenSteps -= static_cast<float>(IncAmt);

		// Update position
		CurrPosition += IncAmt;
		//--------------------------------------------------
	}
	return 0;
}


Any help is appreciated.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// The goal is increment CurrPosition with Velocity, however, CurrPosition must remain an int.
int main()
{
	int 	CurrPosition = 0,	// Current Position
	float 	Velocity = 0.27f,	// Amount of update per iteration
		CurPosFloat = 0.0;	// Current Position as float

	while( CurrPosition < 10 )
	{
		// Increment difference
		CurPosFloat += Velocity

		// Convert float position to int position
		// Multiple conversion options available here.  ceil(), floor(), proper rounding, etc.
		CurrPosition = ceil(CurPosFloat);
	}
	return 0;
}
Opps forgot a detail...
I have to save off IncAmt to use elsewhere.
Topic archived. No new replies allowed.