C++中的純函式


純函式總是為相同引數值返回相同的結果。它們只返回結果且沒有其他副作用,例如引數修改、I/O流、輸出生成等。

一些純函式有sin()、strlen()、sqrt()、max()、pow()、floor()等。一些不純函式有rand()、time()等。

下面是一些展示一些純函式的程式。

strlen()

strlen()函式用於查詢字串的長度。如下程式所示。

示例

 線上演示

#include<iostream>
#include<string.h>
using namespace std;

int main() {
   char str[] = "Rainbows are beautiful";
   int count = 0;

   cout<<"The string is "<< str <<endl;
   cout <<"The length of the string is "<<strlen(str);

   return 0;
}

輸出

以上程式的輸出如下所示。

The string is Rainbows are beautiful
The length of the string is 22

sqrt()

sqrt()函式用於查詢數字的平方根。如下程式所示。

示例

 線上演示

#include<iostream>
#include<cmath>

using namespace std;
int main() {
   int num = 9;

   cout<<"Square root of "<< num <<" is "<<sqrt(num);

   return 0;
}

輸出

以上程式的輸出如下所示。

Square root of 9 is 3

更新日期: 25-6-2020

3K+次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.