2016-01-13 145 views
-3

我想知道是否有代码可以将浮点数转换为如下形式:4.91820238为只有一个小数位的浮点数:4.9不使用C语言库 PS:我不使用print()函数,我想将其转换并且存储它的值?将小数位数多的浮点数转换为浮点数只有一个小数位的浮点数

+2

'convert' ?????或代表?或打印? –

+0

请一直显示您的研究成果。请先阅读[问]页面。 –

+0

printf(“%0.1f”,var_flt); – Ronnie

回答

1

您可以在标准math.h标题中使用fmodf函数。

Then subtract the result from the original

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

int main(void) { 
    float f = 4.9182; 
    printf("%f", f - fmodf(f, 0.1)); 
    return 0; 
} 

编辑:

我从你的意见,你是在独立环境中看到。所以没有标准库。但是,您可以通过查阅参考站点上的示例实现并进行一些内联​​汇编来激发您自己的功能。

0

它转换为整数类型,然后再返回:

float myRound(float f, int num_places) { 
    float factor = 1f; 
    for (i = 0; i < num_places; i++) { 
     factor *= 10f; 
    return ((long long)(factor * (f + .5f)))/factor; 
} 

注意,上面的代码是按照关于浮点数通常的精度/范围的问题。

1

10再除以只需乘以10,做这个

float a = 4.91820238; 
int i; 
i = a*10; 
num = i/10.0; 
// num has 4.9 now 

记住divison期间10.0,如果你只是除以10的时候你就会只得到它的整数商。