21xrx.com
2025-03-28 02:29:56 Friday
文章检索 我的文章 写文章
C++中如何表示乘方操作
2023-07-05 05:41:15 深夜i     23     0
C++ 表示 乘方操作

在C++中,表示乘方操作需要使用指数函数pow()。pow()函数接受两个参数,第一个参数为底数,第二个参数为指数,该函数返回底数的指数次幂的值。

例如,如果要计算3的4次方,我们可以使用以下代码:

#include <iostream>
#include <cmath>
using namespace std;
int main() {
  int base = 3;
  int exponent = 4;
  int result = pow(base, exponent);
  cout << base << " raised to the power of " << exponent << " is: " << result<< endl;
  return 0;
}

输出结果为:

3 raised to the power of 4 is: 81

我们还可以使用指数运算符(**)表示乘方操作:

#include <iostream>
#include <cmath>
using namespace std;
int main() {
  int base = 3;
  int exponent = 4;
  int result = base ** exponent;
  cout << base << " raised to the power of " << exponent << " is: " << result<< endl;
  return 0;
}

输出结果同样为:

3 raised to the power of 4 is: 81

但是需要注意的是,指数运算符在一些旧的编译器中可能不被支持,因此使用指数函数pow()是更加跨平台的选择。

  
  
下一篇: C++暂停功能

评论区

请求出错了