S
S
Sergey Popov2016-01-25 14:26:45
Programming
Sergey Popov, 2016-01-25 14:26:45

How to make a For loop counter of double type?

Exam.
While preparing, I came across a ticket where it is necessary to create a cycle with a step expressed as double. As everyone knows, a real type, when performing actions with it, produces an inexact result. Accordingly, it is necessary to create an algorithm that would display the correct number of actions without crutches.
What method, besides comparing with the epsilon neighborhood and pre-counting the number of steps, can be used?
Thanks in advance.
Wrong cycle code

for(double i = 0; i <=2; i+=0.1){
System.out.println(i);
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MiiNiPaa, 2016-01-25
@be_a_dancer

for(int i = 0; i <=20; i+=1){
    double d = i / 10.0;
    System.out.println(d);
}

A
alexxandr, 2016-01-25
@alexxandr

double max = 20.0;
double current = 0.0;
while (current < max)
{
current += 0.1;
System.out.println(current);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question