while loop – How to make a float number an integer in C?

This is not an easy problem to solve as it may seem at first due to decimal precision and lack of implementation details in your question. Here is an attempt of a solution to your problem, but you might need to adjust it depending on your needs.

#include <stdio.h>
#include <math.h>

#define DELTA 0.00001

int get_number_of_decimal_places(double num)
{
    int count = 0;
    
    do {
        num = num * 10;
        ++count;
    } while (num - (int)num > DELTA);
    
    return count;
}

int main()
{
    double a;
    int result = 0;

    printf("a:");
    scanf("%lf", &a);
    
    int decimal_places = get_number_of_decimal_places(a);
    
    do {
        a *= 10;
        result += (int)a * pow(10, --decimal_places);
        a -= (int)a;
    } while (decimal_places != 0);
    
    printf("result: %d", result);
    getch();
    return 0;
}

For input value 0.12345, the output is:

12345

Keep in mind that this solution treats input values 0.1, 0.0001, 0.010 etc. the same way, so the output would be:

1

Read more here: Source link