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.
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; // ... }
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).
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.
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.
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; // ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With