求大神看一下 ,测试了下第一次循环结尾num的值都是正确的 ,但进入第二次循环a和b的值就没了 导致程序就停止了
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool cmp(char a,char b)
{
return a>b;
}
int tranfnum(string num) //字符串转换为数字
{
int sum = 0;
int t = 1000;
for(int i = 0;i < 4;i++)
{
int n = (num[i]-'0')*t;
sum += n;
t/=10;
}
return sum;
}
string tranchar(int num) //数字转换为字符
{
string result;
int t = 1000;
for(int i = 0;i < 4;i++)
{
if(num < t)
{
result[i] = '0';
t/=10;
continue;
}
result[i] = (num/t) + '0';
num%=t;
t/=10;
}
return result;
}
int main()
{
std::ios::sync_with_stdio(false);
string num,a,b;
cin >> num;
while(1)
{
a = num;b = num;
sort(a.begin(),a.end()); //升序
sort(b.begin(),b.end(),cmp); //降序
int frist = tranfnum(a);
int sconed = tranfnum(b);
int result = sconed - frist;
if(result == 0)
{
cout << b << " - " << a << " = " << 0000 << endl;
break;
}
cout << b << " - " << a << " = ";
int t = 1000;
int temp = result;
while(temp < t)
{
cout << 0;
t/=10;
}
cout << result << endl;
if(result == 6174)
break;
num = tranchar(result);
}
return 0;
}