程序哪里有問題,輸出結(jié)果不正確。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;應(yīng)該放在for循環(huán)之后返回值!你的這個位置只進(jìn)行一次循環(huán)就被終止啦!for循環(huán)中的return中斷了循環(huán)!下次寫代碼時將中括號對應(yīng)起來就好看多啦!
2016-04-09
return temp;應(yīng)該放在for循環(huán)之外,這個位置只進(jìn)行一次循環(huán)就被終止啦!for循環(huán)中的return中斷了循環(huán)!下次寫寫程序的時候要注意層次感,養(yǎng)成一個好的習(xí)慣,對以后的學(xué)習(xí)和編程過程是有百利而無一害的。
2016-04-07
只有一句代碼出錯,就是return temp;此句不應(yīng)該出現(xiàn)在循環(huán)內(nèi),而應(yīng)該出現(xiàn)在循環(huán)外,不知道你注意到了沒有?
修改之后程序運(yùn)行無錯誤。
2016-04-07
// Project01.cpp : 定義控制臺應(yīng)用程序的入口點(diǎn)。
//
#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;
}