[英]My Min and Max number in an array functions shows anything but the Max and Min
Here's my code 这是我的代码
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void buildArray(int arr[], int size) {
srand(time(NULL));
for (int i = 0; i < size; ++i) {
arr[i] = rand() % 100 + 1;
}
}
void showArray(int arr[], int size) {
for (int i = 0; i < size; ++i) {
cout << i << arr[i] << " ";
}
}
void curveArray(int arr[], int size, int curve) {
for (int i = 0; i < size; ++i) {
arr[i] += curve;
}
}
int maxNum(int arr[], int size) {
int maxnum = arr[0];
int position = 0;
for (int i =1; i < size; ++i) {
if (arr[i] > maxnum ) {
maxnum = arr[i];
position = i;
}
}
return position;
}
int minNum(int arr[], int size) {
int minnum = arr[0];
int position = 0;
for (int i =1; i < size; ++i) {
if (arr[i] < minnum) {
minnum = arr[i];
position = i;
}
}
return position;
}
int main()
{
const int size = 10;
int arrayx[size];
buildArray(arrayx, size);
showArray(arrayx, size);
//curveArray(arrayx, size, 5);
//showArray(arrayx, size);
int maxVal = maxNum(arrayx, size);
cout << endl << endl << maxVal;
int minVal = minNum(arrayx, size);
cout << endl << endl << minVal;
return 0;
}
Whenever I try to run this code it generates a random array (as it's supposed exactly) but then when I use the functions to get the Max and Min Values it generates random number so here's the output when I run it 每当我尝试运行此代码时,它都会生成一个随机数组(确切地说是),但是当我使用这些函数获取最大值和最小值时,它会生成一个随机数,因此这是运行它时的输出
http://imageshack.com/a/img27/725/4jv9.png http://imageshack.com/a/img27/725/4jv9.png
This is from a C++ practice video but It works with the tutor but not with me and it's almost the same code!! 这是从C ++练习视频中获得的,但是它与导师一起工作,但对我却不起作用,这几乎是相同的代码!
Your code returns positions of min and max values. 您的代码返回最小值和最大值的位置 。 To take values use 运用价值
int maxVal = arrayx[maxNum(arrayx, size)];
cout << endl << endl << maxVal;
int minVal = arrayx[minNum(arrayx, size)];
cout << endl << endl << minVal;
also your showArray
is incorrect. 而且您的showArray
不正确。 Change it to 更改为
void showArray(int arr[], int size) {
for (int i = 0; i < size; ++i) {
cout << arr[i] << " ";
}
}
You are returning position of Max
and Min
value from the function, not the actual max
and min
values. 您要从函数中返回Max
和Min
位置 ,而不是实际的max
和min
。 It should be 它应该是
return arr[position];
instead of 代替
return position;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.