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

后端 未结 14 1997
旧巷少年郎
旧巷少年郎 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:34

    Try this:

    int main() {
      double num = 23.345;
      int intpart = (int)num;
      double decpart = num - intpart;
      printf("Num = %f, intpart = %d, decpart = %f\n", num, intpart, decpart);
    }
    

    For me, it produces:

    Num = 23.345000, intpart = 23, decpart = 0.345000
    

    Which appears to be what you're asking for.

提交回复
热议问题