結果有問題:為什么我輸入1,得到的最大值是2呢?
#include <stdlib.h>? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? /*包含標準庫的頭文件*/
#include <iostream>? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? /*輸入輸出流的頭文件*/
namespace CompA
{
int getMaxOrMin(int *arr, int cout, bool IsMax)? ? /*定義一個返回值為整形的函數*/
{? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
int temp = arr[0];
for (int i = 1; i < cout; i++)
{
if (IsMax)
{
if (temp < arr[i])
{
temp = arr[i];
}
}
else
{
if (temp > arr[i])
{
temp = arr[i];
}
}
return temp;
}
}
}
int main()
{
bool IsMax = false;
int arr1[4] = {1,2,3,4};
std::cin >> IsMax;
std::cout << CompA::getMaxOrMin(arr1, 4, IsMax)<< std::endl;
system("pause");
return 0;
}
為什么我輸入1,得到的最大值是2呢?
2020-03-24
因為你的return temp;被包含在了for循環中,所以你的for循環實際上只循環了一次(1<2,temp=2),就返回了。