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

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

    I created a subroutine one using a double float, it returns 2 integer values.

    
    void double2Ints(double f, int p, int *i, int *d)
    { 
      // f = float, p=decimal precision, i=integer, d=decimal
      int   li; 
      int   prec=1;
    
      for(int x=p;x>0;x--) 
      {
        prec*=10;
      };  // same as power(10,p)
    
      li = (int) f;              // get integer part
      *d = (int) ((f-li)*prec);  // get decimal part
      *i = li;
    }
    
    void test()
    { 
      double df = 3.14159265;
      int   i,d;
      for(int p=2;p<9;p++)
      {
        double2Ints(df, p, &i,&d); printf("d2i (%d) %f = %d.%d\r\n",p, df,i,d);
      }
    }
    
    

提交回复
热议问题