C++基礎編程DAY3(night)

要求:輸入10個數,求最大值,最小值和平均值

我的代碼

#include<iostream>
#include<stdlib.h>

using namespace std;

int getMax(int *arr)
{
	int temp;
	temp = *arr;
	//cout << temp << endl;
	for(int i=1; i<10; i++)
	{
		//if(temp < (*arr+i))
		if(temp < *(arr+i))
		{
			//temp = (*arr+i);
			temp = *(arr+i);
			//cout << temp << endl;
		}
	}
	return temp;
}

int getMin(int *arr)
{
	int temp;
	temp = arr[0];
	for(int i=1; i<10; i++)
	{
		if(temp > arr[i])
		{
			temp = arr[i];
		}
	}
	return temp;
}

float getAve(int *arr)
{
	float sum = 0;
	sum = arr[0];
	for(int i=1; i<10; i++)
	{
		sum += arr[i];
	}
	return sum/10;
}

int main()
{
	int arr[10] = {0};
	for(int i=0; i<10; i++)
		cin >> arr[i];
	
	//for(int j=0; j<10; j++)
	//	cout << arr[j] ;
	cout << "最大值爲:" << getMax(arr) << endl;
	cout << "最小值爲:" << getMin(arr) << endl;
	cout << "平均值爲:" << getAve(arr) << endl;
	//cout << sizeof(arr)/sizeof(arr[0]) << endl;
	system("pause");
	return 0;
}

題目來源
解答代碼

總結

1、指針做形參時,形參arr的地址指向數組arr[0]的地址,*arr == arr[0],注意區別 (*arr+1) 與 *(arr+1),(arr+1) == arr[0]+1,(arr+1) == arr[1];
2、使用for()循環給數組一一賦值;

思考

輸入任意個數,如何求平均值?詳情自行腦補,以後分解……
求數組長度可用sizeof(arr)/sizeof(arr[0])

發佈了27 篇原創文章 · 獲贊 3 · 訪問量 854
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章