1

Please do flog me for this really basic question, but I still can not get why this happen.

I read that for printing several value behind coma, I should use %.f in C.

So I have this problem, counting 90/100. I expect to print 0.9

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

int main()
{
double c=0;

c = 90/100;
printf("%.1f\n", c);
}

And it shows me 0.0 ..(err..) . tried to change it into (printf("%f\n",c)) return me with 0.00000.. (err..)

Can anyone help me with this? (sorry, really new in programming..)

Thank you

mskfisher
  • 3,291
  • 4
  • 35
  • 48
xambo
  • 399
  • 2
  • 4
  • 17

4 Answers4

9

The problem is that you are doing integer division. 90/100 = 0 in integer terms.

If you want to get 0.9, do : 90.0/100.0

NickLH
  • 2,643
  • 17
  • 28
  • @xambo if this answer answered your question, please click the check mark beside it to mark it as the answer and your problem resolved. – Seth Carnegie Dec 12 '11 at 12:36
  • 2
    @sethCarnegie : yes, I was going to, but I need to wait for couple of minutes before allowed to accept an answer :) – xambo Dec 12 '11 at 12:51
5

The problem is at

c = 90/100;

Although, it will be assigned to a double data type, but the computation itself is all integer and that's why the value is 0.0.

Try,

c = 90.0/100;
Shamim Hafiz - MSFT
  • 21,454
  • 43
  • 116
  • 176
2

it is integer division, do:

c = 90.0/100;
c = (float)90/100;

you need to make atleast one operant a double to evaluate the whole equation as double

phoxis
  • 60,131
  • 14
  • 81
  • 117
1

You are dividing two integers, thus the result is an integer too. Try the following

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

int main()
{
    double c=0;

    c = 90.0/100;
    printf("%.1f\n", c);
}
jhenninger
  • 687
  • 7
  • 12