我正在尝试这个非常简单的问题:
输入:
包含一个整数n (n≤10^6) -序列中元素的数量,后面是ai (1<=i<=n) -序列中的元素
输出:
写出序列的最小奇数和最大偶数。如果没有这样的数字,则写下"-1“而不是这个数字。
输入格式:
5
1 2 3 4 5
输出:1 4
我试过了,但还是不能通过网上评委的审核。
#include <iostream>
//#include <cmath>
using namespace std;
int main()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int n, a, min, max;
cin >> n;
min = INT16_MAX; max = 0;
for (int i = 0; i < n; i++)
{
cin >> a;
if (a >= max && a % 2 == 0) { max = a; }
if (a <= min && a % 2 != 0) { min = a; }
}
if (min == INT16_MAX && min != 1) { min = -1; }
if (max == 0) { max = -1; }
cout << min << " " << max;
return 0;
}为了更好地理解所需的内容,如果输入:
5
2 4 2 5 4
输出应该是:-1 4还是5 4?
发布于 2019-10-02 23:18:10
发布的代码按照以下步骤查找最大偶数
int max = 0;
// ...
{
// ...
if (a >= max && a % 2 == 0) { max = a; }
}
if (max == 0) { max = -1; }但是,引用的问题似乎没有指定输入值的范围。因此,对于每个小于零的偶数值,这将导致错误的结果。
在用于查找最小值的逻辑中也存在类似的问题,该逻辑假设所有奇数值都小于或等于INT16_MIN。
如果输入(...) 2 4 2 5 4输出应该是:-1 4还是5 4?
根据我对所引用问题的理解,输出应该是5 4。如果数字是-1 4,例如2 4 2 6 4(没有奇数)。
为了确保找到的极值是有效的,您可以使用两个标记值,即不能是(最小)奇数的值和不能是(最大)偶数的值:
const int odd_sentinel = 0; // It isn't odd...
const int even_sentinel = -1; // It's not even
int min_odd = odd_sentinel;
int max_even = even_sentinel;
int x;
while ( std::cin >> x )
{
if ( x % 2 )
{
if ( min_odd == odd_sentinel || x < min_odd )
min_odd = x;
}
else
{
if ( max_even == even_sentinel || x > max_even )
max_even = x;
}
}
std::cout << (min_odd == odd_sentinel ? -1 : min_odd) << ' '
<< (max_even == even_sentinel ? -1 : max_even) << '\n';发布于 2019-09-29 18:15:01
min和max应该由值初始化,不能按顺序,否则,你检测不到,你找到这个值了吗,或者它在初始化后没有改变。
发布于 2019-09-29 18:48:46
任务描述建议使用固定大小的数组(106个元素),其中最小和最大是最小奇数和最大偶数的索引,因为没有说明这些数字的值(它们可能都是负数或偶数-1,因此最小和最大没有安全的初始值)。
如果您不想保留所有数字的副本,则可以使用两个布尔变量作为标记是否已初始化最小/最大值的标志:
#include <iostream>
using namespace std;
int main()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int n, a, min, max;
cin >> n;
min = -1; max = -1;
bool minInit = false;
bool maxInit = false;
for (int i = 0; i < n; i++)
{
cin >> a;
if (a % 2 == 0) {
if (!maxInit || a > max) {
maxInit = true;
max = a;
}
} else {
if (!minInit || a < min) {
minInit = true;
min = a;
}
}
}
cout << min << " " << max;
return 0;
}https://stackoverflow.com/questions/58154045
复制相似问题