0

When I cast the double value 44.000000 to int, I get the desired value of 44.

But, When cast the same double value (44.000000) that was derived by some arithmetic operations to int, I get 43.

How can I get rid of this problem and get 44 instead of 43 in the second case?

Below is the code I used,

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

int main(){

    double newd = 44.00;
    printf("Simple Direct Conversion: %d\n\n", (int)newd);

    double d = 100.44;
    double decPart;
    double fracPart = modf(d, &decPart);

    printf("Original Values:      %lf - %lf\n", decPart, fracPart);
    printf("Multiplied by 100:    %lf - %lf\n", decPart * 100, fracPart * 100);
    printf("Converted to Integer: %d - %d\n", (int)(decPart * 100), (int)(fracPart * 100));

    return 0;
}

and the output is,

Simple Direct Conversion: 44

Original Values: 100.000000 - 0.440000

Multiplied by 100: 10000.000000 - 44.000000

Converted to Integer: 10000 - 43

Community
  • 1
  • 1
Sathyamoorthy R
  • 383
  • 4
  • 19
  • 0.44*100 is not 44 [Is floating point math broken?](http://stackoverflow.com/q/588004/995714) – phuclv Feb 08 '17 at 06:30
  • That means your calculation is coming out in the form of 43.xx even if it's 43.99 it will print 43 .go with the calculation and check where you are going wrong. fracPart value – minigeek Feb 08 '17 at 06:30
  • to print `int` use `%d`. [Using the wrong format specifier invokes undefined behavior](http://stackoverflow.com/q/16864552/995714) – phuclv Feb 08 '17 at 06:32
  • @LưuVĩnhPhúc, I get same answer with %d. This is not duplicate. I need explicit answer to get 44. – Sathyamoorthy R Feb 08 '17 at 06:52
  • the fact that it works in your case doesn't mean that's not undefined behavior. Any thing can happen. [What Every C Programmer Should Know About Undefined Behavior](http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html) – phuclv Feb 08 '17 at 07:05
  • So, what are the other possible methods to get 44? any workarounds in case if have? – Sathyamoorthy R Feb 08 '17 at 08:15
  • I fixed myself, printf("Expected Value: %d - %d\n", (int)(round(decPart * 100)), (int)round(fracPart * 100)); – Sathyamoorthy R Feb 08 '17 at 08:46

0 Answers0