我终于完成了这个代码,但是有一个问题:对于输出“Positions:”我希望它输出最小值发生的每个位置。但是,我的代码只输出每个随机生成的数组中的最小位置(大小为20)。请指导我如何在输出最小值的多个位置时减少冗余。谢谢!
#include <iostream>
#include <iomanip>
using namespace std;
double random(unsigned int &seed);
unsigned int seed = (unsigned int)time(0);
const int SIZE = 20;
void print_array (int a[]);
void fill_array (int a []);
int find_min (int [], int);
int main ()
{
int arr[SIZE];
cout << "Arrays: \n";
fill_array(arr);
print_array(arr);
int pos = find_min(arr, SIZE);
int minimum = arr[pos];
cout << "Min is: " << minimum << endl;
cout << "At position: " << pos +1 << endl;
return 0;
}
double random(unsigned int &seed)
{
const int MODULUS = 15749;
const int MULTIPLIER = 69069;
const int INCREMENT = 1;
seed = ((MULTIPLIER*seed)+INCREMENT)%MODULUS;
return double(seed)/MODULUS;
}
void fill_array (int a [])
{
for (int i = 0; i < SIZE; ++i)
a[i] = 0 + (10 * (random(seed)));
}
int find_min (int arr[], int n)
{
int min = arr[0];
int index = 0;
for (int i = 1; i < n; ++i)
if (arr[i] < min)
{
index = i;
min = arr[i];
}
return index;
}
void print_array (int a[])
{
for (int i = 0; i <SIZE; ++i)
cout << setw(3) << a[i];
cout << endl;
}
答案 0 :(得分:0)
您可以通过更改main
来实现目标。请参阅以下代码
int main ()
{
int arr[SIZE];
cout << "Arrays: \n";
fill_array(arr);
print_array(arr);
int pos = find_min(arr, SIZE);
int minimum = arr[pos];
//The following loop traverses through the array and prints the position when array element is equals to minimum
for (int i = pos; i < SIZE; i++) {
if (arr[i] == minimum)
cout << "Min is at: " << i+1 << endl;
}
cout << "Min is: " << minimum << endl;
cout << "At position: " << pos +1 << endl;
return 0;
}
已编辑:要在一行中打印,您可以执行以下代码 -
cout << "Min is at: "
for (int i = pos; i < SIZE; i++) {
if (arr[i] == minimum) {
if (i != pos) cout << ", ";
cout << i+1 << endl;
}
}
但是,有许多格式选项。你可以使用它们中的任何一个。