C语言 如何将浮点数分成整数和小数部分?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23993898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:07:36  来源:igfitidea点击:

How to separate float into an integer and a fractional part?

cfloating-point

提问by TheMatrix

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?

我愿意进行精确的操作,为此我需要一种将浮点数分离为整数和小数部分的方法。有什么办法吗?

回答by Edenia

There is a function included in math.hlibrary called modfWith this function you can do just what are you trying to.

math.h库中包含一个名为modf 的函数。有了这个函数,您就可以做您想做的事。

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 doublein most of the cases is better than using float, despite that doubleconsumes 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 %einstead of %gwhich only uses the shortest representation of the floating decimal.

请注意,double在大多数情况下 using 比 using 更好float,尽管它double消耗了两倍的内存float(4:8 字节),因此增加了范围和准确性。此外,如果您在打印时需要从更大的浮点数中获得更精确的输出,您可以尝试使用printf()指数格式说明符,%e而不是%g仅使用浮点小数的最短表示。

回答by Vishwanath Hiremath 16210107

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);
}

回答by Ankit Jaiswal

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:) .

希望这是您正在寻找的内容:)。