在线编译器 C

#include <stdio.h> int power(int x,int y) { int i=1,last=1; while(i<=y){ last=last*x; i++; }return last; } int main(){ int x,x_save,count=0,o=0; scanf("%d",&x); x_save=x; while(x>0){ count++; x=x/10; }int a[count]; for(int i=count-1;i>=0;i--){ a[i]=x_save%10; x_save=x_save/10; }long long int max=0; int times=count*count,last=count-1; int b[times]; for(int i=0;i<count;i++){ for(last=count-1;last>=0;last--){ int temp=a[i]; a[i]=a[last]; a[last]=temp; for(int j=count-1;j>=0;j--){ max+=power(10,j)*a[4-j]; } }// b[o]=max; o++; } int max_max=b[0]; for(int i=0;i<times;i++){ if(b[i]>max_max){ max_max=b[i]; } } printf("%d",max_max); return 0;}
这段代码试图找出一个整数所有数字排列后能得到的最大值。它先读取一个整数,然后将其各位数字存入数组,再通过交换数字位置生成各种排列,计算每个排列对应的数值,最后找出最大值并输出。

代码中存在几个问题:

- 在生成排列的循环中,`a[4-j]` 这个写法假设数组长度固定为5,但实际数组长度是由输入数字的位数决定的。当输入数字不是4位数时,这里会访问数组越界。

- 生成排列的逻辑不完整。当前只交换了第一位和最后一位,并没有生成所有可能的排列组合。要生成所有排列,通常需要更复杂的算法,比如递归或使用next_permutation的思路。

- 变量 `max` 在每次计算新排列时没有重置为0,导致累加了之前的结果。应该在每次内层循环开始前将 `max` 重新初始化为0。