0

I have another problem of imprecision with float numbers.

#include <stdio.h>
#include <math.h> 
#include <cs50.h>

int main(void)
{    
    float z = 32212254690;
    float y = z / (float)100; 
    printf("%f\n", y);
}

For example, with this piece of code I got an output as 322122560.000000. Can you please explain to me why this happens and how can I produce a number with right floating decimals such as 322122546.90. Thanks

0

If you mean "I want two digits after decimal sign" then you just change your format specifier to %.2f.

So you would use it like this:

printf("%.2f\n", y);

This means that our floating point number will have 2 digits after decimal sign. You can find more info about format specifiers here: format specifiers

3
  • I didn't mean this. This indeed gives me two digits after decimal sign. Instead I want the result to be 322122546.90 just like when you divide 32212254690 by 100. Thanks anyway! – Ali Sarp Mestcioglu Nov 22 '17 at 23:22
  • Oh, you can use double if you need more precision. I think this happens because float has limitation to how much digits it can show, if you want more precision use double (which also has a limit, but the limit is quite larger). – ado387 Nov 23 '17 at 12:17
  • thanks, that solved my problem. – Ali Sarp Mestcioglu Nov 23 '17 at 22:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .