C/C中的幂函数++

给定两个基数和指数,pow()函数会发现x被提升为y的幂,即x Y .基本上,C中的指数是使用pow()函数计算的。pow()是一个求数幂的函数,但我们必须使用#include 在c/c++中使用pow()函数。然后传递两个数字。示例–pow(4,2);然后我们得到的结果是4^2,也就是16。 例子:

null
Input: 2.0, 5.0Output: 32Explanation: pow(2.0, 5.0) executes 2.0 raised tothe power 5.0, which equals 32Input: 5.0, 2.0Output: 25Explanation: pow(5.0, 2.0) executes 5.0 raised tothe power 2.0, which equals 25

语法:

double pow(double x, double y);

参数: 该方法有两个参数:

  • x: 浮点基值
  • y: 浮点幂值

节目:

C

// C program to illustrate
// power function
#include <math.h>
#include <stdio.h>
int main()
{
double x = 6.1, y = 4.8;
// Storing the answer in result.
double result = pow (x, y);
printf ( "%.2lf" , result);
return 0;
}


C++

// CPP program to illustrate
// power function
#include <bits/stdc++.h>
using namespace std;
int main()
{
double x = 6.1, y = 4.8;
// Storing the answer in result.
double result = pow (x, y);
// printing the result upto 2
// decimal place
cout << fixed << setprecision(2) << result << endl;
return 0;
}


输出:

5882.79

pow()函数的整数运算

函数的参数为’double’,返回一个’double’值。这个函数并不总是适用于整数。pow(5,2)就是这样一个例子。当分配给整数时,它在某些编译器上输出24,在其他一些编译器上工作正常。但是pow(5,2)没有任何整数赋值,输出25。

  • 这是因为 2. (即25)可能存储为24.9999999或25.0000000001,因为返回类型为双精度。分配给int时,25.0000000001变为25,但24.9999999将给出24的输出。
  • 为了克服这个问题并以整数格式输出准确的答案,我们可以将1e-9或0.000000001添加到结果中,并将其输入到 智力 e、 g(int)(pow(5,2)+1e-9)将给出正确答案(在上例中为25),而不考虑编译器。

C

// C program to illustrate
// working with integers in
// power function
#include <math.h>
#include <stdio.h>
int main()
{
int a;
// Using typecasting for
// integer result
a = ( int )( pow (5, 2) + 1e-9);
printf ( "%d" , a);
return 0;
}


C++

// CPP program to illustrate
// working with integers in
// power function
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a;
// Using typecasting for
// integer result
a = ( int )( pow (5, 2) + 0.5);
cout << a;
return 0;
}


输出:

25

本文由 阿鲁什·达米加 贾丁·戈亚尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享