任务是:给定一个包含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;
}
此代码现在可以使用。
答案 0 :(得分:1)
这是一个非常模糊的问题,但我注意到,当你使用变量X时,你永远不会把它分配给任何东西。
答案 1 :(得分:0)
这是一种更好的方法,只使用一个阵列,更精确,更干净。希望这可以帮助某人学习。
#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;
}