C将小数值作为int

时间:2018-02-23 23:50:05

标签: c floating-point int

我试图获取数字小数部分的值。我需要数字作为整数。

float x = 12.345; // eventually not hard-coded
int whole = (int)x;
int frac = (x - (float)whole); // this gives 0.345 - expected

x可能是/有任何小数位数。我需要(在我的例子中)345存储在frac

我认为我应该将值存储为字符串/ char [],然后操纵值...

问:我怎样才能得到存储为int的小数的小数值?

2 个答案:

答案 0 :(得分:2)

  

问:我怎样才能得到存储为int的小数的小数值?

使用modff()float分成整数和小数部分。 @Michael Burr

  

modf函数将...分解为整数和小数部分,

#include <math.h>
float x = 12.345;
float whole;
float frac = modff(x, &whole);
  

lrintllrint函数将其参数四舍五入到最接近的整数值,并根据当前的舍入方向进行舍入。

缩放小数部分并进行舍入。

int i = lrintf(frac * 1000);

int whole = (int)x;远远超出x范围时,使用int 未定义的行为

首先将多个x乘以1000的其他方法可能导致舍入不准确或可能溢出。

答案 1 :(得分:0)

我做了一个快速的例程,有你想要的东西。如果您需要更改小数点后的位数,请更改第一个printf中.3f中的3以匹配数字。否则你会看到结果乘以10的倍数或剥离。

有关更多格式选项,请参阅:http://www.cplusplus.com/reference/cstdio/printf/

如果您决定使用更大的数字,我还为数字而不是6分配了10个字节,以降低出错的几率。

&#34;返回0&#34;只是意味着正常退出。这已经在GCC 4.3.3中进行了测试。对于linux而言没有任何警告。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
  float x = 12.345; // your number
  char num[10];     // allocate 10 bytes to store number.
  sprintf(num,"%0.3f",x); //Format number to string with 3 digits past decimal max
  char* frac=strchr(num,(int)'.'); //Find decimal point
  if (frac){ //If decimal found then...
    frac++;    //advance character pointer so we start at wanted number
    printf("%s\n",frac); //as a test, print it as a string
    long int result=strtol(frac,NULL,10); //convert string to long integer
    printf("%ld\n",result); //and print again
  }
  return 0;
}