c++ - 如何在数组中的所有最小值之后放置任何值 X?
问题描述
如果我输入array
,首先代码会找到 ,minimums
然后我想在所有最小值之后输入零。例如
given an array
=1,1,3,1,1
我们看到1s
是最小值,所以结果应该是 =1,0,1,0,3,1,0,1,0
代码
#include <pch.h>
#include <iostream>
int main()
{
int min = 10000;
int n;
std::cout << "Enter the number of elements (n): "; //no of elements in the
std::cin >> n; //array
int *array = new int[2 * n];
std::cout << "Enter the elements" << std::endl;
for (int i = 0; i < n; i++) {
std::cin >> array[i];
if (array[i] > min)
min = array[i];
}
for (int i = 0; i < n; i++) {
if (array[i] == min) { // Not very clear about this
for (int k = n; k > i; k--) // part of the code, my teacher
array[k] = array[k - 1]; //explained it to me , but i
array[i + 1] = 0; // didn't understand (from the
i++; // `for loop k` to be precise)
n++;
}
std::cout << array[i] << ", 0";
}
return 0;
}
但我的回答并没有在最小值之后完全置零
解决方案
第一个问题是计算min
:<
而不是>
.
如果您正在修改参数i
并n
在循环内部,则会出现另一个问题。这是相当危险的,意味着要非常谨慎。
另一个问题是它应该i++; n++;
代替i--,n--;
这是代码:
// #include <pch.h>
#include <iostream>
int main()
{
int min = 1000000;
int n;
std::cout << "Enter the number of elements (n): "; //no of elements in the
std::cin >> n; //array
int *array = new int[2 * n];
std::cout << "Enter the elements" << std::endl;
for (int i = 0; i < n; i++) {
std::cin >> array[i];
if (array[i] < min)
min = array[i];
}
for (int i = 0; i < n; i++) {
if (array[i] == min) { // Not very clear about this
for (int k = n; k > i; k--) // part of the code, my teacher
array[k] = array[k - 1]; //explained it to me , but i
array[i + 1] = 0; // didn't understand (from the)
i++;
n++;
}
}
for (int i = 0; i < n; i++) {
std::cout << array[i] << " ";
}
std::cout << "\n";
return 0;
}
推荐阅读
- reactjs - React.js 应用程序在 axios get 调用上返回 403(禁止)错误代码
- python - Python按列将一维数组添加到二维数组
- performance - 需要帮助找出这个伪代码的时间复杂度
- sql - DB2 SQL:如何将“WHERE EXISTS”表中的列添加到选择语句
- arrays - 当我初始化一个 char 数组而不在 C 中设置数组大小时会发生什么
- javascript - 玩笑:无法使用 `jest.fn()` 保持对模拟函数的引用
- javascript - React Compound Timer 中是否有允许双零的设置
- swift - Swift 和 SwiftUI 之间的 viewContext 是否不同
- python - 如何避免由于库导致 App Engine 空间不足?
- php - Nginx 反向代理为 PHP 返回 404