我们如何提取浮点数的小数部分并将小数部分和整数部分存储到两个单独的整数变量中?
You use the modf
function:
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.
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. 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:
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 .
I created a subroutine one using a double float, it returns 2 integer values.
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
}
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 .
This technique can then be used to get the following decimal characters by using for example 100 instead of 10, and so on.
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.
#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. 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];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.