如何浮动分离成一个整数和小数部分? [英] How to separate float into an integer and a fractional part?

查看:339
本文介绍了如何浮动分离成一个整数和小数部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我愿意投precise操作,并为此目的,我需要一种方法来
单独一个浮点数成整数和小数部分。
是否有这个办法吗?

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?

推荐答案

有在文件math.h 库包含一个函数调用的 MODF
有了这个功能,您可以怎么做是你想。

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

示例:

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

    return fractional;
}

输出:

Floating: 3.40
Integer: 3
Fractional: 0.40

请注意,使用双击在大多数情况下是较好的,然后使用浮动,nomatter的
消耗更多的内存,则浮动(Oftenly 4:8字节)。此外,在情况下,你需要从有precise输出
更大的浮动号码,您可以使用printf的模式%E 而不是%G ,它使用
缩短浮点再presentation。我会用%E 为precision毕竟。

Note that using double in most of the cases is better then using float, nomatter that double consumes more memory then float (Oftenly 4:8 bytes). Also in case you need more precise output from bigger floating numbers, you can use the printf mode %e instead of %g which uses the shorten representation of the floating decimal. I would use %e for precision after all.

这篇关于如何浮动分离成一个整数和小数部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆