函式

Function

函式小百科

概念

遇到地震怎麼辦?

趴下              掩護              穩住             發限動

稱為"躲避地震" 但包含多個動作

好處

方便debug

較容易閱讀

效率較好(有時候)

宣告

宣告 函式名稱(參數)
{
  程式主體;
}

假設我們要寫一個

加法的函式

int sum(int a,int b)
//sum函式的宣告使用int是因為他要回傳整數
{
  return a+b;
}

宣告

#include<bits/stdc++.h>
using namespace std;
int sum(int a,int b)
//sum函式的宣告使用int是因為他要回傳整數
{
  return a+b;
}
int main()
{
  int a,b;
  cin>>a>>b;
  cout<<sum(a,b);
  return 0;
}
#include<bits/stdc++.h>
using namespace std;
void sum(int a,int b)
//sum函式的宣告使用void是因為不回傳
{
  cout<<a+b;
}
int main()
{
  int a,b;
  cin>>a>>b;
  sum(a,b);
  return 0;
}

注意事項

1.注意回傳值的型別

2.參數要分別宣告

ex:int max(int a,int b)

3.void裡面不能return東西

(即可以寫return 但不能寫return a之類的)

4.在函式裡面宣告的變數 出了函式就不能用

TRY TRY SEE

#include<bits/stdc++.h>
using namespace std;
void logic(int a,int b,int c)
{
	a=(a==0)?0:1;
	b=(b==0)?0:1;
	bool out=false;
	if((a&&b)==c)
	{
		cout<<"AND\n";
		out=true;
	}
	if((a||b)==c)
	{
		cout<<"OR\n";
		out=true;
	}
	if((a^b)==c)
	{	
		cout<<"XOR\n";
		out=true;
	}
	if(out==false)
		cout<<"IMPOSSIBLE\n";
}
int main()
{
	int a,b,log;
	while(cin>>a>>b>>log)
		logic(a,b,log);
}

補充說明

(下週內容)

遞迴

在函式裡面呼叫自己

int f(int a)
{
  if(a==1)
  	return 1;
  if(a==2)
  	return 2;
  return f(a-1)+f(a-2);
}

KAHOOT

Function

By ㄌㄌ

Function

  • 66