简体   繁体   English

如何从C中的浮点数中提取小数部分?

[英]How to extract the decimal part from a floating point number in C?

我们如何提取浮点数的小数部分并将小数部分和整数部分存储到两个单独的整数变量中?

You use the modf function:您使用modf函数:

double integral;
double fractional = modf(some_double, &integral);

You can also cast it to an integer, but be warned you may overflow the integer.您也可以将其强制转换为整数,但请注意您可能会溢出整数。 The result is not predictable then.那时的结果是不可预测的。

Try this:试试这个:

int main() {
  double num = 23.345;
  int intpart = (int)num;
  double decpart = num - intpart;
  printf("Num = %f, intpart = %d, decpart = %f\n", num, intpart, decpart);
}

For me, it produces:对我来说,它产生:

Num = 23.345000, intpart = 23, decpart = 0.345000

Which appears to be what you're asking for.这似乎是你所要求的。

The quick "in a nut shell" most obvious answer seems like:快速的“简而言之”最明显的答案似乎是:

#define N_DECIMAL_POINTS_PRECISION (1000) // n = 3. Three decimal points.

float f = 123.456;
int integerPart = (int)f;
int decimalPart = ((int)(f*N_DECIMAL_POINTS_PRECISION)%N_DECIMAL_POINTS_PRECISION);

You would change how many decimal points you want by changing the N_DECIMAL_POINTS_PRECISION to suit your needs.您可以通过更改N_DECIMAL_POINTS_PRECISION以满足您的需要来更改您想要的小数点数。

I think that using string is the correct way to go in this case, since you don't know a priori the number of digits in the decimal part.我认为在这种情况下使用字符串是正确的方法,因为您事先不知道小数部分的位数。 But, it won't work for all cases (eg 1.005), as mentioned before by @SingleNegationElimination.但是,正如@SingleNegationElimination 之前提到的那样,它不适用于所有情况(例如 1.005)。 Here is my take on this:这是我的看法:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char s_value[60], s_integral[60], s_fractional[60];
    int i, found = 0, count = 1, integral, fractional;

    scanf("%s", s_value);

    for (i = 0; s_value[i] != '\0'; i++)
    {
        if (!found)
        {
            if (s_value[i] == '.')
            {
                found = 1;
                s_integral[i] = '\0';
                continue;
            }
            s_integral[i] = s_value[i];
            count++;
        }
        else
            s_fractional[i - count] = s_value[i];
    }
    s_fractional[i - count] = '\0';

    integral = atoi(s_integral);
    fractional = atoi(s_fractional);
    printf("value = %s, integral = %d, fractional = %d\n",
        s_value, integral, fractional);

    return 0;
}

Use the floating number to subtract the floor ed value to get its fractional part:使用浮点数减去floor ed 值得到它的小数部分:

double fractional = some_double - floor(some_double);

This prevents the typecasting to an integer, which may cause overflow if the floating number is very large that an integer value could not even contain it.这可以防止类型转换为整数,如果浮点数非常大以至于整数值甚至无法包含它,这可能会导致溢出

Also for negative values , this code gives you the positive fractional part of the floating number since floor() computes the largest integer value not greater than the input value .同样对于负值,此代码为您提供浮点数的正小数部分,因为floor()计算不大于输入值的最大整数值

I created a subroutine one using a double float, it returns 2 integer values.我使用双浮点数创建了一个子程序,它返回 2 个整数值。


void double2Ints(double f, int p, int *i, int *d)
{ 
  // f = float, p=decimal precision, i=integer, d=decimal
  int   li; 
  int   prec=1;

  for(int x=p;x>0;x--) 
  {
    prec*=10;
  };  // same as power(10,p)

  li = (int) f;              // get integer part
  *d = (int) ((f-li)*prec);  // get decimal part
  *i = li;
}

void test()
{ 
  double df = 3.14159265;
  int   i,d;
  for(int p=2;p<9;p++)
  {
    double2Ints(df, p, &i,&d); printf("d2i (%d) %f = %d.%d\r\n",p, df,i,d);
  }
}

Here is another way:这是另一种方式:

#include <stdlib.h>
int main()
{
    char* inStr = "123.4567";         //the number we want to convert
    char* endptr;                     //unused char ptr for strtod

    char* loc = strchr(inStr, '.');
    long mantissa = strtod(loc+1, endptr);
    long whole = strtod(inStr, endptr);

    printf("whole: %d \n", whole);     //whole number portion
    printf("mantissa: %d", mantissa);  //decimal portion

}

http://codepad.org/jyHoBALU http://codepad.org/jyHoBALU

Output:输出:

whole: 123 
mantissa: 4567

Even I was thinking how to do it.连我都在想怎么做。 But I found a way.但我找到了办法。 Try this code试试这个代码

printf("Enter a floating number");
scanf("%d%c%d", &no, &dot, &dec);
printf("Number=%d Decimal part=%d", no, dec);

Output:-输出:-

Enter a floating number
23.13
Number=23 Decimal part=13

I made this function, it seems to work fine:我做了这个功能,它似乎工作正常:

#include <math.h>

void GetFloattoInt (double fnum, long precision, long *pe, long *pd)
{
  long pe_sign;
  long intpart;
  float decpart;

  if(fnum>=0)
  {
    pe_sign=1;
  }
  else
  {
    pe_sign=-1;
  }

  intpart=(long)fnum;
  decpart=fnum-intpart;

  *pe=intpart;  
  *pd=(((long)(decpart*pe_sign*pow(10,precision)))%(long)pow(10,precision));
}

If you just want to get the first decimal value, the solution is really simple.如果你只想得到第一个十进制值,解决方法很简单。

Here's an explanatory example:这是一个解释性示例:

int leftSideOfDecimalPoint = (int) initialFloatValue; // The cast from float to int keeps only the integer part

int temp = (int) initialFloatValue * 10;
int rightSideOfDecimalPoint = temp % 10;

Say for example we have an initial float value of 27.8 .例如,我们有一个初始浮点值 27.8 。

  • By just casting the initial float value to an int, you discard the fraction part and only keep the integer part.通过将初始浮点值转换为 int,您可以丢弃小数部分并只保留整数部分。
  • By multiplying the initial float value by 10 we get a result of 278.0, then by casting this result to int, gives you the value of 278通过将初始浮点值乘以 10,我们得到 278.0 的结果,然后将此结果转换为 int,得到值 278
  • If we divide 278 by 10, we get 27.8, of which the remainder is 8, which is the value at the right side of the decimal point. 278除以10得到27.8,余数为8,即小数点右边的值。 Thus use modulus.因此使用模数。

This technique can then be used to get the following decimal characters by using for example 100 instead of 10, and so on.然后可以使用此技术通过使用例如 100 而不是 10 等来获取以下十进制字符。


Just take note that if you use this technique on real-time systems, for example to display it on a 7-segment display, it may not work properly because we are multiplying with a float value, where multiplication takes a lot of overhead time.请注意,如果您在实时系统上使用此技术,例如在 7 段显示器上显示它,它可能无法正常工作,因为我们乘以浮点值,乘法需要大量开销时间。

 #include <stdio.h>
Int main ()
{
float f=56.75;
int a=(int)f;
int result=(f-a)*100;
printf ("integer = %d\n decimal part to integer 
 =%d\n",result);
}
Output:- 
integer =56
decimal part to integer = 75

假设 A 是您的整数,则 (int)A,表示将数字转换为整数并将是整数部分,另一个是 (A - (int)A)*10^n,这里 n 是要保留的小数位数.

Maybe the best idea is to solve the problem while the data is in String format.也许最好的想法是在数据为字符串格式时解决问题。 If you have the data as String, you may parse it according to the decimal point.如果你的数据是String,你可以根据小数点来解析。 You extract the integral and decimal part as Substrings and then convert these substrings to actual integers.您将整数和小数部分提取为子字符串,然后将这些子字符串转换为实际整数。

float num;
int intgPart;
float fracPart;
printf("Enter the positive floating point number: ");
scanf("%f", &num);

intgPart = (int)num;
fracPart = num - intgPart;

The fractional part can be obtained by subtracting an integral part from the original double value.小数部分可以通过从原始双精度值中减去整数部分得到。

cout<<"enter a decimal number\n";
cin>>str;
for(i=0;i<str.size();i++)
{
    if(str[i]=='.')
    break;
}

for(j=i+1;j<str.size();j++)
{
    cout<<str[j];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM