程序哪里有問題,輸出結果不正確。min 5和max10(10,5,19,3)
#include <stdlib.h>
#include <iostream>
using namespace std;
int getMaxOrMin(int *arr, int count, bool isMax)
{
int temp = arr[0];
for (int i = 1; i < count; i++)
{
if (isMax)
{
if (temp < arr[i])
{
temp = arr[i];
}
}
else
{
if (temp > arr[i])
{
temp = arr[i];
}
}
return temp;
}
}
int main(void)
{
bool isMax=false;
int arr1[4] = {10,5,19,3 };
cin >> isMax;
cout << getMaxOrMin(arr1,4, isMax)<<endl;
system("pause");
return 0;
}
2016-04-07
return temp;應該放在for循環之后返回值!你的這個位置只進行一次循環就被終止啦!for循環中的return中斷了循環!下次寫代碼時將中括號對應起來就好看多啦!
2016-04-09
return temp;應該放在for循環之外,這個位置只進行一次循環就被終止啦!for循環中的return中斷了循環!下次寫寫程序的時候要注意層次感,養成一個好的習慣,對以后的學習和編程過程是有百利而無一害的。
2016-04-07
只有一句代碼出錯,就是return temp;此句不應該出現在循環內,而應該出現在循環外,不知道你注意到了沒有?
修改之后程序運行無錯誤。
2016-04-07
// Project01.cpp : 定義控制臺應用程序的入口點。
//
#include <StdAfx.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int getMaxOrMin(int *arr, int count, bool isMax)
{
int temp = arr[0];
for (int i = 1; i < count; i++)
{
if (isMax)
{
if (temp < arr[i])
{
temp = arr[i];
}
}
else
{
if (temp > arr[i])
{
temp = arr[i];
}
}
}return temp;
}
int main(void)
{
bool isMax=false;
int arr1[4] = {10,5,19,3 };
cin >> isMax;
cout << getMaxOrMin(arr1,4, isMax)<<endl;
system("pause");
return 0;
}