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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP