如何制作“位置”?在我的代码更精确? [英] How do I make the "position" in my code more precise?
本文介绍了如何制作“位置”?在我的代码更精确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我终于为一个赋值完成了这个代码但是有一个问题:对于输出Positions:我希望它输出最小值发生的每个位置。但是,我的代码只输出每个随机生成的数组中的最小位置(大小为20)。
I finally finished this code for an assignment but there is one problem: for the output "Positions:" I want it to output every position where the minimum occurs. However, my code only outputs the last position of the minimum in each randomly generated array (size 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;
}
我的尝试:
我不明白如何添加更多位置值,因为数组大小为20,无论如何,最小值将至少打印两次。
What I have tried:
I don't understand how to add more position values since the array size is 20 and no matter what, the minimum will be printed at least twice.
推荐答案
编写另一个函数:FindNext。
交给它数组,它的大小,要查找的值,以及开始的索引。
如果找到另一个例子,返回索引。如果不这样做,请返回-1。
然后循环调用并打印最小值,直到找不到它为止。
但这是你的作业,所以我不会给你任何代码!
Write another function: FindNext.
Hand it the array and it's size, the value to look for, and the index to start at.
If you find another example, return the index. If you don't, return -1.
Then loop calling that and printing minima until it can't find any more.
But this is your homework, so I'll give you no code!
这篇关于如何制作“位置”?在我的代码更精确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文