我的代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
bool cmp(int a, int b)
{
return a > b;
}
int main()
{
int a, res[10];
cin >> a;
if (a == 6174) printf("7641 - 1467 = 6174\n");
int z = a;
int j = 0;
while (z)
{
res[j ++ ] = z % 10;
z /= 10;
}
bool flag = false;
for (int n = 0; n < j; n ++ )
if (res[n] != res[0])
{
flag = true;
break;
}
memset(res, 0, sizeof res);
if (!flag) printf("%d - %d = 0000", a, a);
else
{
while (a != 6174)
{
int i = 0, x, y;
while (a)
{
res[i ++ ] = a % 10;
a /= 10;
}
sort(res, res + 4, cmp);
x = res[0] * 1000 + res[1] * 100 + res[2] * 10 + res[3];
y = res[3] * 1000 + res[2] * 100 + res[1] * 10 + res[0];
a = x - y;
printf("%04d - %04d = %04d\n", x, y, a);
memset(res, 0, sizeof res);
}
}
return 0;
}
改好了,有帮助望采纳,谢谢!
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
bool cmp(int a, int b)
{
return a > b;
}
int main()
{
int a, res[10];
cin >> a;
if (a == 6174) printf("7641 - 1467 = 6174\n");
if(a<10) a*=1000; //改的地方一
int z = a;
int j = 0;
while (z)
{
res[j ++ ] = z % 10;
z /= 10;
}
bool flag = false;
for (int n = 0; n < j; n ++ )
if (res[n] != res[0])
{
flag = true;
break;
}
memset(res, 0, sizeof res);
if (!flag) printf("%04d - %04d = 0000", a, a); //改的地方二
else
{
while (a != 6174)
{
int i = 0, x, y;
while (a)
{
res[i ++ ] = a % 10;
a /= 10;
}
sort(res, res + 4, cmp);
x = res[0] * 1000 + res[1] * 100 + res[2] * 10 + res[3];
y = res[3] * 1000 + res[2] * 100 + res[1] * 10 + res[0];
a = x - y;
printf("%04d - %04d = %04d\n", x, y, a);
memset(res, 0, sizeof res);
}
}
return 0;
}
题主考虑的太复杂了,前面的判断冗余了,修改如下,供参考:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
bool cmp(int a, int b)
{
return a > b;
}
int main()
{
int a, res[4] = {0};
cin >> a;
/*if (a == 6174) printf("7641 - 1467 = 6174\n");
//int z = a;
//int j = 0;
//while (z)
//{
// res[j++] = z % 10;
// z /= 10;
//}
//bool flag = false;
//for (int n = 0; n < j; n++)
// if (res[n] != res[0])
// {
// flag = true;
// break;
// }
//memset(res, 0, sizeof res);
//if (!flag) printf("%d - %d = 0000", a, a);
//else
//{*/
while (1)// while (a != 6174)
{
int i = 0, x, y;
while (a)
{
res[i++] = a % 10;
a /= 10;
}
sort(res, res + 4, cmp);
x = res[0] * 1000 + res[1] * 100 + res[2] * 10 + res[3];
y = res[3] * 1000 + res[2] * 100 + res[1] * 10 + res[0];
a = x - y;
printf("%d%d%d%d", res[0], res[1], res[2], res[3]);
printf(" - %d%d%d%d = %04d\n", res[3], res[2], res[1], res[0], a);
memset(res, 0, sizeof(res));
if (a == 6174 || a == 0) //这里增加循环退出判断
break;
}
//}
return 0;
}