这是我的代码
#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;
}
每当我尝试运行此代码时,它会生成一个随机数组(正如它所说的那样),但是当我使用这些函数获取最大值和最小值时,它会生成随机数,所以这是我运行时的输出
http://imageshack.com/a/img27/725/4jv9.png
这是来自C ++练习视频,但它与导师合作,但不适合我,它几乎是相同的代码!
答案 0 :(得分:1)
您的代码返回最小值和最大值的位置。要使用值
int maxVal = arrayx[maxNum(arrayx, size)];
cout << endl << endl << maxVal;
int minVal = arrayx[minNum(arrayx, size)];
cout << endl << endl << minVal;
您的showArray
也不正确。将其更改为
void showArray(int arr[], int size) {
for (int i = 0; i < size; ++i) {
cout << arr[i] << " ";
}
}
答案 1 :(得分:1)
您要从函数返回Max
和Min
值的位置,而不是实际的max
和min
值。它应该是
return arr[position];
而不是
return position;