Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for-loop, increment by double

Tags:

I want to use the for loop for my problem, not while. Is it possible to do the following?:

for(double i = 0; i < 10.0; i+0.25) 

I want to add double values.

like image 591
UpCat Avatar asked Oct 19 '10 18:10

UpCat


People also ask

How do you do double increment in a for loop?

To prevent being bitten by artifacts of floating point arithmetic, you might want to use an integer loop variable and derive the floating point value you need inside your loop: for (int n = 0; n <= 40; n++) { double i = 0.25 * n; // ... }

Can you do for loops with doubles?

Using a double in a for loop requires careful consideration since repeated addition of a constant to a floating point can cause accumulating total to "go off" due to inexact conversions from decimal to binary. (Try it with i += 0.1 as the incrementation and see for yourself).

What is i ++ and ++ i in for loop?

Both increment the number, but ++i increments the number before the current expression is evaluted, whereas i++ increments the number after the expression is evaluated.

What does i ++ mean in a for loop?

In the condition section ( i < 2 ) we test to see if our counter value ( i ) is equal to our limit/condition value ( 2 ). And in the increment section ( i++ ) we increase the value of our counter value every time we complete a loop of the FOR loop.


1 Answers

To prevent being bitten by artifacts of floating point arithmetic, you might want to use an integer loop variable and derive the floating point value you need inside your loop:

for (int n = 0; n <= 40; n++) {     double i = 0.25 * n;     // ... } 
like image 63
rsp Avatar answered Nov 14 '22 01:11

rsp