C++與演算法

內建函式

C++本身就已經有許多寫好的函式可以使用,稱之為內建函式

在使用內建函式之前必須先 引入 對應的 函式庫


語法 - 引入函式庫

  • 寫在程式的ㄧ開始
#include<函式庫名稱>



表格 - 常見的內建函式

函式庫 函式 功能 回傳值型態
math.h sqrt( float x ) 回傳 x 的開根號值 float
pow( float x, float y ) 回傳 x 的 y 次方 float
ctype.h isalpha( char c ) 回傳 c 是不是英文字母 bool
isdigit( char c ) 回傳 c 是不是數字 bool
string.h strlen( char s[] ) 回傳 s 的長度 int



範例 - 開根號計算器

input

9
64
144

output

3
8
12

code

  • 因為使用 sqrt 函式,所以先引入 math.h 函式庫
#include<iostream>
#include<math.h>                   // <--------
using namespace std;

int main()
{
    float x;

    while( cin >> x )
    {
        cout << sqrt(x) << endl;   // <--------
    }

    return 0;
}