Онлайн компилятор C

#include <stdio.h> int main() { char n[100]; scanf("%s", n); int i = 0; int found = 0; while (n[i] != '\0') { int max = n[i]; int record = i; for (int j = i; n[j] != '\0'; j++) { if (n[j] > max) { max = n[j]; record = j; found = 1; } } if (found) { break; } else { i++; } } if (found) { int temp = n[i]; n[i] = n[record]; n[record] = temp; } printf("%s", n); return 0; }
这段代码试图在输入的字符串中找到第一个可以交换的位置,使得交换后字符串的字典序变大。具体来说,它从左到右扫描每个字符,对于每个位置 i,在它后面的字符中寻找一个比它大的最大字符,如果找到就交换并停止。

代码中存在逻辑错误,导致它不能正确完成这个任务。

- 变量 `found` 在每次进入 while 循环时没有重置,导致一旦某个位置后面有更大的字符,`found` 就会一直为 1,后续的 i 递增逻辑失效。实际上,你需要在每次检查新位置 i 时重新设置 `found` 为 0。
- 交换时使用的 `n[i]` 和 `n[record]` 是在 while 循环外部,但 `record` 是在循环内部赋值的。如果 `found` 为 1 时循环已经 break,那么 `record` 的值是正确的;但如果循环正常结束(没有找到任何可交换的位置),`record` 的值可能未定义。你需要确保只有在找到可交换位置时才执行交换。