MOTIVECODEX
MOTIVECODEX

Reputation: 2752

Exchange 1000s digit with 10s digit (C)

I am trying to switch for example: input 54321.987, then 4 and 2 should switch, so output would be 52341.987. 54321.777 should become 52341.777. If it is 2345.777 it should be 4325.777. Anything less than that I do not care about. But if it was like 888886543.777 only the second and fourth numbers should be switch from the most right part before the comma. So it would become 888884563.777

So as LearningC suggested, I am trying to exchange only the 1000s digit with the 10s digit.

But whatever I try, I get errors. I can't pass the errors. How shall I do this?

What I have so far that actually works is just this:

   int main(int argc, char** argv) {
        double x;
        scanf("%lf", &x);

        double tens = ((int) (x / 10)) % 10;
        double thousands = ((int) (x / 1000)) % 10;

        printf("%09.3f", x += (tens - thousands) * 990.0);
        return 0;
    }

The code above now works.

Upvotes: 1

Views: 158

Answers (3)

abelenky
abelenky

Reputation: 64702

I just wrote this:

double swapDigits(double in)
{
    return in + ((int)(in / 10) % 10 - (int)(in / 1000) % 10) * 990.0;
}

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

Reputation: 754280

Using string manipulation:

char string[20];

snprintf(string, sizeof(string), "%09.3f", x);
char *dot = strchr(string, '.');
assert(dot != 0 && dot > string + 4);
char old_4 = dot[-4];
char old_2 = dot[-2];
dot[-2] = old_4;
dot[-4] = old_2;

/* If you need a float back */
sscanf(string, "%lf", &x);

Using arithmetic manipulation:

double frac_part;
double int_part;

frac_part = modf(x, &int_part);

long value = int_part;
int  dig_2 = (int_part / 10) % 10;
int  dig_4 = (int_part / 1000) % 1000;
assert(dig_4 != 0);
value -= 10 * dig_2 + 1000 * dig_4;
value += 10 * dig_4 + 1000 * dig_2;
int_part = value;
x = int_part + frac_part;

Neither sequence of operations is minimal, but they are fairly straight-forward.

Upvotes: 1

glglgl
glglgl

Reputation: 91069

First, you have to determine these digits.

You can do so with

double tens = ((int)(x / 10)) % 10;
double thousands = ((int)(x / 1000)) % 10;

which enables you to do

x = x - (tens * 10.0) - (thousands * 1000.0) + (tens * 1000.0) + (thousands * 10.0);

which subtracts them at their original place and re-adds them in a swapped way.

You can optimize this to

x = x + tens * (1000.0 - 10.0) - thousands * (1000.0 - 10.0);

and, again, this to

x += (tens - thousands) * 990.0;

Upvotes: 6

Related Questions