wafflesausage
wafflesausage

Reputation: 395

Displaying Digits Beginning from 0.000000001 to 0.999999999 in C

I'm trying to print out the numbers mentioned in the title with a loop with the following code:

#include <stdio.h>
int ceiling = 1;
float counter = 0;
int main()
{
while (counter < ceiling)
{
    printf("%f\n", counter);
    counter = counter + 0.000000001;
}
}

but it only gives me 7 digits of precision. Is there any way to get 10 digits of precision?

Upvotes: 1

Views: 285

Answers (1)

paddy
paddy

Reputation: 63481

You won't get that precision out of a float. Even with double you may end up with rounding errors during the count that could appear to skip or repeat some numbers. In a pinch, you can use double with 9 decimal places like this:

printf( "%.9f\n", counter );

But consider using an int instead. This will handle all 9-digit numbers you need. And you just print them with zero-padding:

int counter = 0;
int ceiling = 1000000000;
while( counter < ceiling ) {
    printf( "0.%09d\n", counter );
    counter++;
}

The above will of course print trailing zeros. It's not clear whether you want that or not.

Upvotes: 4

Related Questions