floating point - Exchange 1000s digit with 10s digit (C) -
i trying switch example: input 54321.987, 4 , 2 should switch, output 52341.987. 54321.777 should become 52341.777. if 2345.777 should 4325.777. less not care about. if 888886543.777 second , fourth numbers should switch right part before comma. become 888884563.777
so learningc suggested, trying exchange 1000s digit 10s digit.
but whatever try, errors. can't pass errors. how shall this?
what have far works 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 works.
first, have determine these digits.
you can with
double tens = ((int)(x / 10)) % 10; double thousands = ((int)(x / 1000)) % 10; which enables do
x = x - (tens * 10.0) - (thousands * 1000.0) + (tens * 1000.0) + (thousands * 10.0); which subtracts them @ original place , re-adds them in swapped way.
you can optimize to
x = x + tens * (1000.0 - 10.0) - thousands * (1000.0 - 10.0); and, again, to
x += (tens - thousands) * 990.0;
Comments
Post a Comment