How to extract the decimal part from a floating point number in C?

后端 未结 14 1900
旧巷少年郎
旧巷少年郎 2020-11-27 04:04

How can we extract the decimal part of a floating point number and store the decimal part and the integer part into two separate integer variables?

相关标签:
14条回答
  • 2020-11-27 04:53

    Even I was thinking how to do it. But I found a way. Try this code

    printf("Enter a floating number");
    scanf("%d%c%d", &no, &dot, &dec);
    printf("Number=%d Decimal part=%d", no, dec);
    

    Output:-

    Enter a floating number
    23.13
    Number=23 Decimal part=13
    
    0 讨论(0)
  • 2020-11-27 04:54

    Use the floating number to subtract the floored value to get its fractional part:

    double fractional = some_double - floor(some_double);
    

    This prevents the typecasting to an integer, which may cause overflow if the floating number is very large that an integer value could not even contain it.

    Also for negative values, this code gives you the positive fractional part of the floating number since floor() computes the largest integer value not greater than the input value.

    0 讨论(0)
提交回复
热议问题