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

后端 未结 14 2034
旧巷少年郎
旧巷少年郎 2020-11-27 04:04

How can we extract the decimal part of a floating point number and store the decimal part and the integer part into two separate integer variables?

14条回答
  •  半阙折子戏
    2020-11-27 04:52

    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 (e.g. 1.005), as mentioned before by @SingleNegationElimination. Here is my take on this:

    #include 
    #include 
    
    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;
    }
    

提交回复
热议问题