Sullivan Sullivan - 1 month ago 7
C Question

Switching the the 2nd and 4th digit from right(rightmost) in a double

My question is pretty much the same as the question asked here: question

The difference is that I want to switch the 2nd and 4th digit from the right, instead of the left like in the other question. So rightmost number in my case is 1.
Example: 283926.67 becomes 282936.67.
How do I code this?

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


int main() {


double number;

printf("Give a number: ");
scanf("%lf", &number);

//printf("%.4f", number);

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

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

number = atof(arr);
printf("%.4f\n", number);


return 0;
}

Answer

You just have to do the exact same thing as in the link you've given:

int main() {
    double A = 282936.67;

    char str[50];
    sprintf(str, "%f", A);

    int dot = -1, i = 0;
    //Finds the dot position
    while (i != 50) {
        if (str[i] == '.') {
            dot = i;
            break;
        }
        i++;
    }

    if (dot >= 4) {
        char tmp = str[dot - 2];//Search from the dot position
        str[dot - 2] = str[dot - 4];
        str[dot - 4] = tmp;
    }
    //Convert your string to a float
    A = atof(str);
    printf("%.2f", A);

    while (1);
    return 0;
}
Comments