如何在C++中获得立方根
How can I obtain the cube root in C++?
我知道如何使用sqrt
函数获得数字的平方根。
如何获得一个数字的立方根?
sqrt
代表"平方根","平方根"表示提升到1/2
的幂。根本不存在"平方根为2"或"平方根的根为3"这样的东西。对于其他词根,您可以更改第一个单词在您的情况下,您正在寻求如何执行立方体根。
在C++11之前,没有具体的函数,但你可以回到第一个原则:
- 平方根:
std::pow(n, 1/2.)
(或std::sqrt(n)
) - 多维数据集根:
std::pow(n, 1/3.)
(或自C++11以来的std::cbrt(n)
) - 第四根:
std::pow(n, 1/4.)
- 等等
如果您希望传递n
的负值,请避免使用std::pow
解决方案—它不支持分数指数的负输入,这就是为什么添加了std::cbrt
:
std::cout << std::pow(-8, 1/3.) << 'n'; // Output: -nan
std::cout << std::cbrt(-8) << 'n'; // Output: -2
注意:.
真的很重要,因为否则1/3
使用整数除法并得到0
在C++11中std::cbrt
是作为数学库的一部分引入的,您可以参考
include <cmath>
std::pow(n, 1./3.)
此外,在C++11中,在同一报头中存在cbrt
。
傻瓜数学。
x的第n个根等于x^(1/n),因此使用std::pow
。但我不明白这与运算符重载有什么关系。
只是为了指出这一点,尽管我们可以使用两种方式,但
long long res = pow(1e9, 1.0/3);
long long res2 = cbrt(1e9);
cout<<res<<endl;
cout<<res2<<endl;
返回
999
1000
因此,为了使用pow函数获得正确的结果,我们需要在实际数字上添加0.5的偏移量,或者使用双重数据类型,即
long long res = pow(1e9+0.5, 1.0/3)
double res = pow(1e9, 1.0/3)
这里更详细的解释C++pow不同寻常的类型转换
实际上,必须进行上述解决方案才能工作。
正确的解决方案是
ans=圆形(pow(n,1/3.));
这个问题的解决方案是
cube_root = pow(n,(float)1/3);
你应该#include <math.h>
库文件
旧的C/C++标准不支持cbrt()函数
当我们编写像cube_root = pow(n,1/3);
这样的代码时,编译器认为1/3 = 0
(C/C++中的除法问题),所以你需要使用(float)1/3
进行类型转换,以获得正确的答案
#include<iostream.h>
#include<conio.h>
#include<math.h>
using namespace std;
int main(){
float n = 64 , cube_root ;
clrscr();
cube_root = pow(n , (float)1/3);
cout<<"cube root = "<<cube_root<<endl;
getch();
return 0;
}
立方根=4
你可以试试这个C算法:
// return a number that, when multiplied by itself twice, makes N.
unsigned cube_root(unsigned n){
unsigned a = 0, b;
for (int c = sizeof(unsigned) * CHAR_BIT / 3 * 3 ; c >= 0; c -= 3) {
a <<= 1;
b = 3 * a * (a + 1) + 1;
if (n >> c >= b)
n -= b << c, ++a;
}
return a;
}
我会劝阻以上任何方法,因为它们对我都不起作用。我做了pow(64,1/3.)和pow(64,1./3.),但得到的答案是3
这是我的逻辑
ans = pow(n, 1/3.);
if (pow(ans, 3) != n){
ans++;
}