c++ - 在 C++ 中的数组中找到 2 个数字的最小值
问题描述
#include <iostream>
using namespace std;
int main()
{
int a[42] = {-16748, 1861305,
-1677019, 2959868,
8279642, -5614317,
-6959809, -8869681,
5841371, 684147,
9078506, -9854715,
5442553, -8007477,
5455657, 400271,
-8326571, -589876,
-2139466, 7869921,
9462518, 8289564,
-1158751, -1908990,
3315049, 5073796,
-2511851, 6631645,
960911, 5459324,
9951099, 7368220,
1403411, -6792887,
2886747, 4303636,
-4393903, -1918146,
-2402605, -1947543,
-6002778, -7925503,
};
int b[21];
for (int i=0; i<=42; i+=2)
{
int n=0;
if (i == 0) {
if (a[i] > a[i+1])
b[i] = a[i+1];
else if (a[i] < a[i+1])
b[i] = a[i];
}
else if (i > 0) {
if (a[i] > a[i+1])
b[i-n] = a[i+1];
else if (a[i] < a[i+1]) {
b[i-n] = a[i];
}
}
n++;
}
for (int i=0; i<=21; i++)
cout << b[i] << " ";
return 0;
}
我正在解决一个寻找两者之间最小值的问题,但我没有得到正确的输出
输出如下所示:
-16748 32765 -1677019 0 -5614317 32765 -8869681 32560 684147 32560 -9854715 0 -8007477 32560 400271 32560 -8326571 0 -2139466 32765 8289564 0
我已经尝试了 30 分钟,但没有成功。
注意:我是 C++ 的初学者
解决方案
您需要更正多个陈述。
首先
for (int i=0; i<=42; i+=2)
你的数组大小是 42,所以循环的索引是从 0 到 41(含)。但是,您的循环也达到 42,这将导致未定义的行为(这通常是不好的),所以正确的方法是
for (int i=0; i < 42; i+=2)
同样,当您打印时b
,
for (int i=0; i<=21; i++) //incorrect
for (int i=0; i < 21; i++) //correct
最后,找到最小值的代码,可以像这样更容易地完成,
for (int i=0; i < 42; i+=2)
{
b[i/2] = min(a[i], a[i + 1]);
}
// OR you can do this
for (int i=0; i < 21; i++)
{
b[i] = min(a[2 * i], a[2 * i + 1]);
}
推荐阅读
- android - 如何使用 Android Jetpack 执行条件导航?
- r - 在不同向量上多次执行相同步骤的更简单方法?
- kotlin - 如何解析 DayOfWeek 范围
- angular - 如何在谷歌地图上加载 GeoJSON?
- regex - 正则表达式匹配第一次出现斜线之后的所有内容,直到第二次出现斜线
- javascript - 具有排序功能的 MutationObserver 中的无限循环
- tensorflow - AttributeError: KerasTPUModel' 对象没有属性 _ckpt_saved_epoch
- git - 2 个版本之间的 Git 日志差异
- android - 尝试使用 firebase ml vision 读取图像上的文本时应用程序崩溃
- excel - 如何更新宏中的公式范围?