C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

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

  1. C ++の文字列at()関数

    このセクションでは、C ++のat()関数とは何かを説明します。 at()関数は、特定の位置にある文字にアクセスするために使用されます。 このプログラムでは、at()関数を使用して各文字を繰り返し処理し、それらを異なる行に出力します。 サンプルコード #include<iostream> using namespace std; main() {    string my_str = "Hello World";    for(int i = 0; i<my_str.length(); i++) {  

  2. C ++のstrchr()関数

    C ++では、strchr()は事前定義された関数です。文字列の処理に使用され、指定された文字列内の特定の文字の最初の出現を返します。 strchr()の構文は次のとおりです。 char *strchr( const char *str, int c) 上記の構文で、strは文字cを含む文字列です。 strchr()関数は、str内で最初に出現するcを検出します。 strchr()関数を示すプログラムは次のとおりです。 例 #include <iostream> #include <cstring> using namespace std; int main()