C++ function

常用內建函式

swap:(交換兩個variable)

#include <utility>
int a = 3, b = 4;
swap(a, b);

abs:(取絕對值)

#include <cmath>
int a = 3, b = 4;
abs(a);
b = abs(b);

max/min:

#include <algorithm>
int a = 3, b = 4;
cout << max(a, b);

sqrt:(開根號)

#include <cmath>
int a = 25;
cout << sqrt(a);

pow:(次方)

#include <cmath>
cout << pow(2, 3);

ceil、floor:

double a = 3.3;
cout << ceil(a) <<" " 
<< floor(a);

為什麼需要函式

 

同樣的東西不想要重複寫,希望縮短程式碼

 

main():其實也是一個函式

萬用標頭檔

#include <bits/stdc++.h>

把常用的標準函式全部include,像是

iostream

vector

string

algorithm

cmath

不是標準的使用方式,但在寫小程式很適合使用

函式

函式的組成

  • 名稱
  • 參數
  • 回傳值
int abs(int n);

系統定義的函式通常定義在標頭檔裡面

要使用需要先引入(#include)標頭檔

標頭檔不一定包含程式的實作,只有定義如何使用而已

如何自己寫函式

  • 用之前要先宣告
#include <iostream>
using namespace std;
int f(int x, int y)
{
	return x +y;
}
int main()
{
	cout << f(2, 3);
    return 0;
}
#include <iostream>
using namespace std;
int f(int x, int y);
int main()
{
	cout << f(2, 3);
    return 0;
}
int f(int x, int y)
{
	return x + y;
}

函式宣告

int f(int x, int y);
bool leapYear(int y);
string Input();
void printHelloworld();

void代表沒有->無回傳值

參數(argument)前面也要寫下參數的type

Return

  • return回傳值須和所宣告的符合
  • return 後會跳回呼叫此函式的程式部分
#include <iostream>
using namespace std;
int my_min(int a, int b)
{
    return a < b ? a : b;
}
int main ()
{
    int a = 5, b = 4;
    cout << my_min(a, b)<<"\n";
    return 0;
}

void func

#include <iostream>
using namespace std;
void foo(int i)
{
    cout << "foo: "<<i<<"\n";
    return;
    cout << "hi\n";
}
int main ()
{
    int a = 5, b = 4;
    foo(a);
    return 0;
}

練習:a006 一元二次方程式

Call by value

void myswap(int a, int b)
{
	int tmp = a;
    a = b;
    b = tmp;
}
int main()
{
	int x = 5, y = 3;
    myswap(x, y);
    cout << x <<" " << y <<"\n";
}

會將x和y先複製到另外一個記憶體

Call by reference

void myswap(int &a, int &b)
{
	int tmp = a;
    a = b;
    b = tmp;
}
int main()
{
	int x = 5, y = 3;
    myswap(x, y);
    cout << x <<" " << y <<"\n";
}

將原本的x和y直接傳給程式

Remark: call by reference傳過去的值一定要是變數

Const

只能讀不能寫(不能改變)

const int x = 4;
void f(const int &x)
{
	cout << x + 3 << "\n";
}
int main()
{
	f(3);//可以接受
}

local variables vs gloabl variables

#include <iostream>
using namespace std;
int g = 4; // 全域變數
int f(int x)
{
	int y = 3; //x, y 區域變數
	return (x + y) % g;
}
int main()
{
	int a = 5;
    a = f(a);
    cout << a <<"\n";
}

local variables執行完函式後會消失

#define (macro)

#include <iostream>
#define pi 3.141592
#define f(x) (x)*(x)
using namespace std;
int main()
{
	cout << f(3 + 1);
}

純文字替換

作業:

  • a158
  • d039
  • c675

C++ function

By ernestii26