How to separate float into an integer and a fracti

2020-03-14 02:14发布

问题:

I am willing to cast precise operations and for that purpose I need a way to seperate a float number into an integer and a fractional part. Is there any way for this?

回答1:

There is a function included in math.h library called modf With this function you can do just what are you trying to.

Example:

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

double ftof ()
{
    double floating = 3.40, fractional, integer;

    fractional = modf(floating, &integer);
    printf ("Floating: %g\nInteger: %g\nFractional: %g", floating, integer, fractional); // when using printf, there are no floats

    return fractional;
}

Output:

Floating: 3.40
Integer: 3
Fractional: 0.40

Note that using double in most of the cases is better than using float, despite that double consumes twice the memory of float (4:8 bytes) hence the increased range and accuracy. Also in case you need more precise output from bigger floating numbers when printing, you can try the printf() exponent format specifier %e instead of %g which only uses the shortest representation of the floating decimal.



回答2:

One other way using type cast.

#include <stdio.h> 
#include <math.h>
void main()
{ 
    float a = 3.4;
    float a_frac = a - (int) a;
    float a_int = a - a_frac;
    printf("Number = %f, Integer = %f, Fraction = %f", a, a_frac, a_int);
}


回答3:

A thought crossed my mind to separate them with some logic :

    #include <iostream>

using namespace std;
int main()
    {
    double fr,i,in,num=12.7;
    for(i=0;i<num;i++)
    {
        fr=num-i;
        }
        cout<<"num: "<<num;
cout<<"\nfraction: "<<fr;
in=num-fr;
cout<<"\nInteger: "<<in;
    }

Hope this was what you were searching for:) .