在 C++ 中查找数字的第 n 个根
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21141447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find nth Root of a number in C++
提问by user3198803
I'm trying to make a maths library and one of the functions finds a nth root of a float.
我正在尝试创建一个数学库,其中一个函数找到浮点数的第 n 个根。
My current expression is -
我现在的表达是——
value = value ^ 1/rootValue
but I'm getting an error because I'm using a float. Is there another method of solving this?
但我收到一个错误,因为我使用的是浮点数。有没有另一种方法来解决这个问题?
回答by Mike Seymour
There is no "power" operator in C++; ^
is the bitwise exclusive-or operator, which is only applicable to integers.
C++ 中没有“power”运算符;^
是按位异或运算符,仅适用于整数。
Instead, there is a function in the standard library:
相反,标准库中有一个函数:
#include <cmath>
value = std::pow(value, 1.0/root);
回答by starsplusplus
^
is not what you want here. It is a bitwise exclusive-OR operator.
^
不是你想要的。它是一个按位异或运算符。
Use
用
#include <math.h>
and then
进而
value = pow(value, 1/rootvalue)
Reference for pow
: http://www.cplusplus.com/reference/cmath/pow/
回答by Am33d
^is Bitwise XORoperator. Use the pow()function for it.
^是 按位异或运算符。使用pow()函数。
回答by Life
According to the wikipage,
根据维基页面,
#include <iostream>
using namespace std;
double exp(double, double);
double n_root_(double, double);
int main()
{
double v = n_root_(27,3);
cout << v << endl;
return 0;
}
double exp(double a, double b){
double t(1);
for(int i = 0;i<b;++i)
t *= a;
return t;
}
double n_root_(double num, double n_){
double x;
double A(num);
double dx;
double eps(10e-6);
double n(n_);
x = A * 0.5;
dx = (A/exp(x,n-1)-x)/n;
while(dx >= eps || dx <= -eps){
x = x + dx;
dx = (A/exp(x,n-1)-x)/n;
}
return x;
}