【问题标题】:C get fractional value as intC获取小数值为int
【发布时间】:2018-02-23 23:50:05
【问题描述】:

我正在尝试获取数字小数部分的值。但是,我需要将数字作为整数。

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 的小数的小数值?

【问题讨论】:

  • 12.112.001 的结果应该是什么。他们应该都是1吗?
  • 对于固定的 3 位小数:乘以 1000 并使用 %
  • 请注意,由于浮点的性质,对于float x = 0.3,您可能会得到 299。
  • ...乘以 1000,round 到最接近的int,并使用%
  • 要获得小数部分,您可能需要查看modf() 系列函数。在不知道有效位数的情况下获得“任意长度的小数位”对我来说没有意义(正如@Barmar 的问题所暗示的那样)。能解释清楚点吗?

标签: c floating-point int


【解决方案1】:

问:如何获取存储为 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);

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

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

【讨论】:

    【解决方案2】:

    我做了一个快速的例程,其中包含您正在寻找的内容。如果您需要更改小数点后的位数,请更改第一个 printf 中 .3f 中的 3 以匹配数字。否则,您将看到结果乘以 10 的倍数或被剥离。

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

    我还为该数字分配了 10 个字节而不是 6 个字节,以在您决定使用更大的数字时降低出错的可能性。

    “return 0”只是表示正常退出。这已在 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-16
      • 2019-06-09
      • 2014-01-25
      • 2016-11-14
      • 2016-05-12
      • 2011-02-08
      • 2010-10-30
      相关资源
      最近更新 更多