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