给定一个整数数组 A(20).将 Min 元素放在数组的开头
Given an array of integers A(20). Put Min element in the beginning of the array
任务是:给定一个包含 20 个整数 A(20) 的数组。在其中找到最小正整数并将其放在数组的开头。显示初始数组和更改的数组。
我的代码是(现在可以工作了):
#include <iostream>
using namespace std;
int main(){
int arrayA[20]={6,7,8,9,10,11,12,1,2,3,4,5,13,14,15,16,17,18,19,20};
int min=arrayA[0];
int i, minplace;
//array's showing in the screen
cout<<"Array A: n";
for(i=0; i<20; i++)
cout<<arrayA[i]<<" ";
cout<<endl;
//min value of array's element
for(int i=0; i<20; i++)
if (arrayA[i]<min)
{
min=arrayA[i];
minplace=i;
}
cout<<"Min element's value of the array A: "<<min<<endl;
//array 2
int arrayB[21]={min,6,7,8,9,10,11,12,1,2,3,4,5,13,14,15,16,17,18,19,20};
//array's showing in the screen
cout<<"Array B: n";
for(i=0; i<21; i++)
cout<<arrayB[i]<<" ";
cout<<endl;
int k=minplace+1;
int n=21;
for (int i=minplace+1; i<n; i++)
arrayB[i]=arrayB[i+1];
n=n-1;
cout<<"Array with deleted element: "<<endl;
for (int i=0; i<n; i++)
cout<<arrayB[i]<<" ";
return 0;
}
此代码现在有效。
这是一个非常模糊的问题,但我确实注意到,当你使用变量X时,你永远不会把它分配给任何东西。
这是一种更好的方法,它只使用单个数组,并且更精确和干净。希望这可能有助于某人学习。
#include <iostream>
using namespace std;
int main(){
int arrSize = 20;
int myArray[20] = {6,7,8,9,10,11,12,1,2,3,4,5,13,14,15,16,17,18,19,20};
cout<<"Initial Array:t";
/* loop for printing the initial array */
for(int i = 0; i<arrSize; i++)
cout<< myArray[i]<< " ";
/* assuming the first element of the array is the minimum */
int minIndex = 0;
int min = myArray[minIndex];
/* loop for finding the minimum value */
for(int i = 0; i<arrSize; i++){
/* condition for checking if the current element is the minimum */
if(myArray[i]<min){
min = myArray[i];
minIndex = i;
}
}
/* swaping the first element of the array with the minimum element */
myArray[minIndex] = myArray[0];
myArray[0] = min;
cout<<"nFinal Array:t";
/* loop for printing the final array */
for(int i = 0; i<arrSize; i++)
cout<< myArray[i] << " ";
return 0;
}
相关文章:
- 数组元素打印的递归方法
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 std::map 中插入数组元素
- 使用指针访问数组元素时出现意外结果
- c++ 使用动态分配运算符反向数组元素
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- 缺少数组元素问题
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 删除在结构 c++ 中声明的数组元素
- Getter 和 Setter 用于类 C++ 中的数组元素
- 尝试递归获取数组元素的总和
- 使用SWIG将numpy数组元素(int)传递给c++int