gpt4 book ai didi

c++ - 为什么pow(x,1/p)和pow(x,1.0/p)不相等,即使打印它们的值会得到相同的结果

转载 作者:行者123 更新时间:2023-12-02 09:48:03 25 4
gpt4 key购买 nike

问题是:

You are given 2 numbers (N , M); the task is to find N√M (Nth root of M).

Input:

The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains two space separated integers N and M.

Output:

For each test case, in a new line, print an integer denoting Nth root of M if the root is an integer else print -1.


现在我对这个问题的解决方案是:
#include <math.h>
#include <iostream>
#include <math.h>
using namespace std;

int main() {
int t;
float x, p;
cin>>t;
for(int i=0;i<t;i++)
{
cin>>p>>x;
if(p==0)
{
cout<<"1"<<endl;

}

else
{
float res=pow(x,(1/p));
cout<<"res="<<res<<endl;
if(res==int(res))
cout<<res<<endl;
else
cout<<"-1"<<endl;
}
}
return 0;
}
这在测试用例中引起了问题:
1个
3
1000

虽然当我打印 res时得到的结果是 10,但在条件检查期间 if(res==int(res))证明是假的。
我也注意到从 float res=pow(x,(1/p));更改为 float res=pow(x,(1.0/p));给出了正确的答案。我猜想它与完成 0.33333的评估时获取 1/p有关,但是我不明白为什么打印的值是 10但在条件检查中不匹配。

最佳答案

Why are pow(x,1/p) and pow(x,1.0/p) not equal even though printing their values gives the same result (?)


计算因精度而异。计算在数学上并不精确: pow()接收的精确值不是1/3。
使用 float p1/p可以与 1.0/p不同,因为第一个使用 float(或更宽)数学完成,第二个使用 double(或更宽),因为1.0是 double
依次调用 floatdouble pow()。因此,可能存在不同的 res结果。
在OP的情况下: pow(1000.0f,(1/3.0f))执行了 float精度计算,类似于 pow(1000, near_one_third)而不是 cbrt(1000.0)-结果不完全是 10.0fpow(1000.0f,(1.0/3.0f))进行了类似的 double精度计算,当四舍五入为 float时,该精确度就是 10.0f

why the printed value is 10 but not matching in the condition checking.


如果 res的计算值大于或小于 10.0f,则 ==不正确。
以足够的精度打印,以查看最终输出中的差异。推荐 float res至少9个有效数字。

至少,我建议始终使用相同的浮点类型和数学运算。 (将1.0f与 float一起使用。)进一步建议使用 double
不过,最终输出仍可能不是 pow()的确切预期整数(来自数学分析)。

关于c++ - 为什么pow(x,1/p)和pow(x,1.0/p)不相等,即使打印它们的值会得到相同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63472425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com