Tuğbars Heptaşkın
Tuğbars Heptaşkın

Reputation: 41

splitting a float into fractions and integrals using C

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

    sprintf(s_value, "%f", f);

    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);

    return integral;
}

Hello, I am trying to make a program which splits a float number into integral part(as int) and fractional part(as int). It would be also a QoL upgrade for me if the program stores these in an array and returns that array.(In the example code the implementation returns only one integer.) For example, 682.1 should return, 682 and 1.(in an array preferably) I want my program to find "." in the given argument, make a new integer from integrals and make another integer from fractions.

At online IDE's my code works, however on my atmel solution I get "conflicting types for "Decimalsplit" error. I'd like to hear from you about where the problem is.

Upvotes: 0

Views: 225

Answers (1)

pmg
pmg

Reputation: 108978

program [...] returns [...] array

quote heavily edited

You can wrap the array in a struct

#include <stdio.h>

struct Arr2 { int data[2]; };

struct Arr2 foo(double x) {
    struct Arr2 r;
    r.data[0] = x;
    r.data[1] = (x - r.data[0]) * 1000000;
    return r;
}

int main(void) {
    struct Arr2 split;
    split = foo(3.14159);
    printf("%d + 0.%06d\n", split.data[0], split.data[1]);
    return 0;
}

https://ideone.com/NmTvxn

Upvotes: 2

Related Questions