Loop Paradoxon

Hi,

my problem is that I am writing a counter that counts in fractions:

eg.:
 
 0/5, 1/5, 2/5, 3/5, 4/5, 5/5

 0.0, 0.2, 0.4, 0.6, 0.8, 1.0



But if I write it with floats my programm will not count to 1.0 if I count in 1/10, 1/20, 1/30, 1/70, 1/80 ...
Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <cstdlib>
#include <iostream>
using namespace std;

//denumerator
#define N      60

int main(int argc, char *argv[])
{
    
    cout << "0.0 to 1.0 in 1/" << N << " steps:\n\n";
    
    for (float i = 0.0; i <= 1.0; i += 1.0/N)
        cout << i << endl;
    
    cout << endl;
    
    system("PAUSE");
    return 0;
}


Could this be caused by a float overflow or something similar?

Thanks in advance ^^
It is not a problem with float overflow, but it is a problem with floats.

http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
To put it simply, never use floats in loop conditions. Use ints & find some mathematical formula to convert them to float or double inside the loop (Not tested):

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

#include <iostream>

int main(int argc, char *argv[])
{

//denominator
const int N = 60; //prefer this to using a #define. Alternatively use constexpr in C++11

double DecimalFraction  = 0.0;
    
    std::cout << "0.0 to 1.0 in 1/" << N << " steps:\n\n";
    
    for (int i = 0; i < N; ++i) { // always uses braces even when there is 1 statement
        DecimalFraction = static_cast<double>(i) / N;
        std::cout << i << " divided by " << N << " is " << DecimalFraction << "\n";
    }

    std::cout << std::endl; // flushes the buffer
    
    system("PAUSE");  // read the article about why this isn't good
    return 0;
}


HTH
Topic archived. No new replies allowed.