最萌皮卡丘 2022-08-09 15:02 采纳率: 0%
浏览 64

pow()函数的运行机制

我用C++做个开x的n次方根的程序,可是一直不明白pow()函数是什么代码求 pow(x, 1 / n)。
希望回答pow()函数的代码,不是返回另一个函数的那种(递归是可以的),希望能刨根问底到最基础的那层函数。
我最多搜到这里:

  using ::pow;

#ifndef __CORRECT_ISO_CPP_MATH_H_PROTO
  inline _GLIBCXX_CONSTEXPR float
  pow(float __x, float __y)
  { return __builtin_powf(__x, __y); }

  inline _GLIBCXX_CONSTEXPR long double
  pow(long double __x, long double __y)
  { return __builtin_powl(__x, __y); }

#if __cplusplus < 201103L
  // _GLIBCXX_RESOLVE_LIB_DEFECTS
  // DR 550. What should the return type of pow(float,int) be?
  inline double
  pow(double __x, int __i)
  { return __builtin_powi(__x, __i); }

  inline float
  pow(float __x, int __n)
  { return __builtin_powif(__x, __n); }

  inline long double
  pow(long double __x, int __n)
  { return __builtin_powil(__x, __n); }
#endif
#endif

  template<typename _Tp, typename _Up>
    inline _GLIBCXX_CONSTEXPR
    typename __gnu_cxx::__promote_2<_Tp, _Up>::__type
    pow(_Tp __x, _Up __y)
    {
      typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type;
      return pow(__type(__x), __type(__y));
    }

感谢每一个回答!

  • 写回答

3条回答 默认 最新

  • KaMtuo 2022-08-09 15:37
    关注

    n是整数吗,整数可以这样写,不是整数就很复杂了,不会。

    /*----------------------------------*/
    /* Author : KaMtuo                  */
    /* Email : kamtuo@qq.com            */
    /* Creation_time : 2022-08-09 15:12 */
    /* Software : Visual Studio Code    */
    /*----------------------------------*/
    
    #include <iostream>
    #include <algorithm>
    #include <cstring>
    #include <cstdio>
    #include <queue>
    #include <vector>
    #include <map>
    #include <cmath>
    
    #define endl "\n"
    
    using std::cin;
    using std::cout;
    using std::max;
    using std::min;
    using std::sort;
    using std::queue;
    using std::priority_queue;
    using std::vector;
    using std::map;
    using std::string;
    
    
    double doublepow(double a, int b) {
        double l = 0, r = a;
        while (r - l >= 1e-6) {
            double mid = (l + r) / 2.0;
            double k = 1.0;
            for (int i = 1; i <= b; i ++) k *= mid;
            if (k >= a) r = mid;
            else l = mid; 
        }
        return l;
    }
    
    
    int main() {
        double a, n;
        cin >> a >> n;
        printf("%.6lf\n", doublepow(a, n));
        return 0;
    }
    

    这个可以满足不是整数的情况,不过用了其他函数,不符合要求了。

    double doublepow(double a, double b) {
        return exp(log(a) * b);
    }
    
    评论

报告相同问题?

问题事件

  • 创建了问题 8月9日

悬赏问题

  • ¥15 找别人艾特你然后删除的微博
  • ¥15 idea做图书管理系统,要求如下
  • ¥15 最短路径分配法——多路径分配
  • ¥15 SQL server 2022安装程序(英语)无法卸载
  • ¥15 关于#c++#的问题:把一个三位数的素数写在另一个三位数素数的后面
  • ¥15 求一个nao机器人跳舞的程序
  • ¥15 anaconda下载后spyder内无法正常运行
  • ¥20 统计PDF文件指定词语的出现的页码
  • ¥50 分析一个亿级消息接收处理策略的问题?
  • ¥20 uniapp 朋友圈分享单页面自定义操作