Rich Mirin Rich Mirin - 2 months ago 8
C Question

How to switch 2nd and 4th digit(before comma) in a double? C programming

So lets say the input is 45392.56, the output has to be 49352.56.
How can i program this in C?

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

int main() {
    double d = 45392.56;

    char arr[sizeof(d)];
    snprintf(arr, sizeof(d) + 1, "%f", d);

    char aux = arr[1];
    arr[1] = arr[3];
    arr[3] = aux;

    d = atof(arr);
    printf("%.2f\n", d);
}

Output:

49352.56
Comments