交换1000位数字与10位数字(C)

我试图切换例如:输入54321.987,然后4和2应该切换,所以输出将是52341.987。 54321.777应该成为52341.777。 如果它是2345.777,它应该是4325.777。 比我不关心的任何东西。 但如果它像888886543.777那样只有第二个和第四个数字应该从逗号之前的最右边部分切换。 所以它会变成888884563.777

因此,正如LearningC建议的那样,我试图仅用1000s数字与10s数字交换。

但无论我尝试什么,我都会遇到错误。 我无法传递错误。 我该怎么做?

到目前为止,实际上有效的是:

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; } 

上面的代码现在有效。

首先,您必须确定这些数字。

你可以这样做

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

这使你能够做到

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

它们在原始位置减去它们并以交换方式重新添加它们。

你可以优化它

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

再次,这个

 x += (tens - thousands) * 990.0; 

使用字符串操作:

 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); 

使用算术操作:

 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; 

这两个操作序列都不是最小的,但它们相当简单。

我刚刚写了这个:

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