-1

How do I return a double without getting rounded:

int function() {
    double d = 5.894; 
    printf("d=%f\n", d);
    return d;
}

int main() {
    double d = function();
    printf("d=%f\n", d);
    return 0;
}

This gives me

d=5.894000
d=5.000000

What am I missing here?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Tom
  • 2,545
  • 5
  • 31
  • 71
  • can someone explain the downvote?! – Tom Feb 03 '16 at 17:35
  • so yeah?! I am waiting for an explanation ! – Tom Feb 03 '16 at 17:57
  • Just reviewed this question in triage, did not vote, but I have an explanation: many would consider this too simple to deserve a question on StackOverflow. – Alexei - check Codidact Feb 03 '16 at 20:13
  • I know that but why? I did several C tutorials, none of them mentioned this. Also when I google this it's not very clear that you need this. Stackoverflow is also for beginners not only for advanced stuff. I did my research and spent enough time on that, I am sorry that I am just a beginner and didn't see that but that was my problems. Forums like these should be there for cases like that. The least thing I can expect is a rebuttal to that. – Tom Feb 03 '16 at 20:56
  • ok, so now, that I complained, I see that I got one downvote removed. This seems to be completely random. I'll just go downvote whatever I want to, too. – Tom Feb 03 '16 at 21:19

2 Answers2

6

Your function returns ٰint it must return double

Change

int function()

to

double function()
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
1

iharob's answer is of course correct, but I think that it is also important to know how to avoid this kind of errors in the future.

I have also have not found any explicit reference of this behavior (implicit cast from a "large" numeric type to a "smaller" one), so I have asked a question about this.

Shortly put, by providing the correct compilation warning flags, these errors can be spotted at compile time (e.g. -Wconversion), as it's almost always a bug.

However, this behavior is by design, and as mentioned by Chris in a comment, sometimes it might be useful in terms of performance.

Community
  • 1
  • 1
Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164