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