Exchange 1000s digit with 10s digit (C)

前端 未结 3 1960
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-16 10:45

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

相关标签:
3条回答
  • 2021-01-16 11:17

    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.

    0 讨论(0)
  • 2021-01-16 11:21

    I just wrote this:

    double swapDigits(double in)
    {
        return in + ((int)(in / 10) % 10 - (int)(in / 1000) % 10) * 990.0;
    }
    
    0 讨论(0)
  • 2021-01-16 11:33

    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;
    
    0 讨论(0)
提交回复
热议问题