2020-02-18 18:02

# PAT乙级1019数字黑洞2，3，4测试点无法通过

20

``````#include<iostream>
#include<string>
#include<algorithm>
using namespace std;

bool cmp(char a, char b)
{
return a > b;
}
int main()
{
char number1[4], number2[4];
int n = 0;
for (int i = 0; i < 4; i++)
{
cin>>number1[i];
}
if (number1[0] == number1[1]&& number1[1]== number1[2]&& number1[2]== number1[3])//4位数字相同时的输出
{
for (int i = 0; i < 4; i++)
{
cout << number1[i];
}
printf(" - ");
for (int i = 0; i < 4; i++)
{
cout << number1[i];
}
printf(" = 0000");
}
else//其他情况
{

while (n != 6174)
{
for (int i = 0; i < 4; i++)
{
number2[i] = number1[i];
}
sort(number1, number1 + 4, cmp);//较大的数
sort(number2, number2 + 4);//较小的数
for (int i = 0; i < 4; i++)//输出相减的两个数
{
cout << number1[i];
}
printf(" - ");
for (int i = 0; i < 4; i++)
{
cout << number2[i];
}

int n1 = 0, n2 = 0,t=1;
for (int i = 3; i >=0; i--)//输出相减结果
{
n1 += ((int)number1[i]-48) * t;
t *= 10;
}
t = 1;
for (int i = 3; i >= 0; i--)
{
n2 += ((int)number2[i]-48) * t;
t *= 10;
}
n = n1 - n2;
printf(" = %04d\n", n);

int temp = n;
int i = 0;
while(i<4)//记录相减的结果
{
number1[i++] = (char)(temp % 10+48);
temp /= 10;
}
}

}
return 0;
}
``````
• 点赞
• 写回答
• 关注问题
• 收藏
• 复制链接分享
• 邀请回答

#### 2条回答

• 我搜索到了题目，你注意看

输入格式：
输入给出一个`(0, 10000)`区间内的正整数N。

你没有考虑<10000的情况

如果是 < 10000，你的程序还在等待输入，而实际上应该是补0

我把输入修改了下，你看看行不行

``````// Q1055005.cpp : Defines the entry point for the console application.
//

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;

bool cmp(char a, char b)
{
return a > b;
}
int main()
{
char number1[4], number2[4];
int n = 0;
int input;
cin >> input;
for (int i = 0; i < 4; i++)
{
number1[4-i-1] = input % 10 + '0';
input /= 10;
}
if (number1[0] == number1[1]&& number1[1]== number1[2]&& number1[2]== number1[3])//4位数字相同时的输出
{
for (int i = 0; i < 4; i++)
{
cout << number1[i];
}
printf(" - ");
for (int i = 0; i < 4; i++)
{
cout << number1[i];
}
printf(" = 0000");
}
else//其他情况
{

while (n != 6174)
{
for (int i = 0; i < 4; i++)
{
number2[i] = number1[i];
}
sort(number1, number1 + 4, cmp);//较大的数
sort(number2, number2 + 4);//较小的数
for (int i = 0; i < 4; i++)//输出相减的两个数
{
cout << number1[i];
}
printf(" - ");
for (int i = 0; i < 4; i++)
{
cout << number2[i];
}

int n1 = 0, n2 = 0,t=1;
for (int i = 3; i >=0; i--)//输出相减结果
{
n1 += ((int)number1[i]-48) * t;
t *= 10;
}
t = 1;
for (int i = 3; i >= 0; i--)
{
n2 += ((int)number2[i]-48) * t;
t *= 10;
}
n = n1 - n2;
printf(" = %04d\n", n);

int temp = n;
int i = 0;
while(i<4)//记录相减的结果
{
number1[i++] = (char)(temp % 10+48);
temp /= 10;
}
}

}
return 0;
}

``````

# 问题解决的话，请点下采纳，谢谢合作

点赞 1 评论 复制链接分享
• 才4位数，不需要使用char，还以为是超大数！
https://blog.bccn.net/xianfajushi/66963

https://blog.bccn.net/xianfajushi/66961

点赞 评论 复制链接分享