我试图让这个函数返回数组中的最高元素。我使用指针在数组中输入元素。代码运行后,仅显示数组中的第一个元素。 我尝试使用此代码 int SIZE = sizeof(ptr) / sizeof(ptr[0]);在主函数中,但我遇到了变量重新定义错误。请帮忙
#include <iostream>
using namespace std;
double gethighest(const double ptr[], int SIZE)
{
double highest = ptr[0];
for (int count = 0; count < SIZE; count++)
{
if (ptr[count] > highest)
highest = ptr[count];
return highest;
}
}
int main()
{
double* ptr = nullptr;
int SIZE;
double value;
cout << "Enter the size of the array" << endl;
cin >> SIZE;
ptr = new double[SIZE];
for (int count = 0; count < SIZE; count++)
{
cout << "Enter the values of the array: ";
cin >> ptr[count];
while (ptr[count] < 0)
{
cout << "Invalid entry, enter a positive value: ";
cin >> ptr[count];
}
}
double highest = gethighest(ptr, SIZE);
cout << "The highest value of the array is: " << highest;
}
问题是你
return highest
在循环内。您需要在看完所有数字后将其归还:
double gethighest(const double ptr[], int SIZE) {
double highest = ptr[0];
for (int count = 1; count < SIZE; count++) {
if (ptr[count] > highest) highest = ptr[count];
}
return highest; // return _after_ the loop
}