我正在尝试创建一个程序来查找整数数组中的最小整数。这是我的代码:
#include<iostream>
using namespace std;
int findMinimum(int array);
int findMinimum(int array){
int arraySize = sizeof(array)/sizeof(int);
int minimum = array[0];
for (int i = 0; i < arraySize; i++){
if (arraySize[i] < minimum){
minimum = arraySize[i];
}
}
return minimum;
}
int main(){
int array[7] = {17,2,10,291,28,10,11};
int minimum = findMinimum(array);
cout << "The minimum of the array is: " << minimum;
}
我收到此错误:
/Users/Danny/Desktop/C++/Practice/arrays.cpp:9:22: error: subscripted value is not an array, pointer, or vector
int minimum = array[0];
~~~~~^~
/Users/Danny/Desktop/C++/Practice/arrays.cpp:11:18: error: subscripted value is not an array, pointer, or vector
if (arraySize[i] < minimum){
~~~~~~~~~^~
/Users/Danny/Desktop/C++/Practice/arrays.cpp:12:26: error: subscripted value is not an array, pointer, or vector
minimum = arraySize[i];
~~~~~~~~~^~
/Users/Danny/Desktop/C++/Practice/arrays.cpp:20:17: error: no matching function for call to 'findMinimum'
int minimum = findMinimum(array);
^~~~~~~~~~~
/Users/Danny/Desktop/C++/Practice/arrays.cpp:7:5: note: candidate function not viable: no known conversion from 'int [7]' to 'int' for 1st argument
int findMinimum(int array){
如何解决这些错误?谢谢。
答案 0 :(得分:3)
功能头应该是:
int findMinimum(int* array)
但是,对于int*
,这不起作用:
int arraySize = sizeof(array)/sizeof(int);
因此你也应该将大小传递给函数:
int findMinimum(int* array, int size)
您还应该考虑使用std :: vector而不是数组。
答案 1 :(得分:2)
这可能是作弊:
#include <algorithm>
#include <iostream>
#include <iterator>
int main() {
int array[7] = { 17, 2, 10, 291, 28, 10, 11 };
int min = *std::min_element(std::begin(array), std::end(array));
std::cout << "The minimum of the array is: " << min << '\n';
return 0;
}
答案 2 :(得分:1)
你在这一行传递的内容
int minimum = findMinimum(array);
实际上是指向int
数组的指针......实际上是指向第一个元素的指针。因此,您希望将功能签名更改为
int findMinimum(int* array)
在修改后的函数int findMinimum(int* array)
中,下面的行将是错误的
int arraySize = sizeof(array)/sizeof(int);
因为array
已经是分解指针了...所以你想再次将函数改为
int findMinimum(int* array, int size)
您的完整计划将是:
#include<iostream>
using namespace std;
int findMinimum(int* array, int arraySize);
int findMinimum(int* array, int arraySize){
int minimum = array[0];
for (int i = 0; i < arraySize; i++){
if (arraySize[i] < minimum){
minimum = arraySize[i];
}
}
return minimum;
}
int main(){
int array[7] = {17,2,10,291,28,10,11};
int minimum = findMinimum(array, sizeof(array)/sizeof(int));
cout << "The minimum of the array is: " << minimum;
}