我们如何找到 N sqrt(m) 并检查答案是否是 C++ 中的整数

how can we find n sqrt(m) and check whether the answer is an integer in c++

本文关键字:是否是 答案 检查 C++ 整数 何找 sqrt 我们      更新时间:2023-10-16

这是我尝试过的方法,所以如果您有任何建议,请提供帮助。使用模板可以解决这个问题吗

#include <iostream>
`#include<math.h> 
 using namespace std;
int main()
{
 long double m=0;
long double n=0,ans=0;//is this wrong
 int t;
cin>>t;
for(int i=0;i<t;i++)//here t is testcases
{
   cin>>n>>m;
   ans=pow(m,1.0/n);
   if(floor(ans)==ans)//this is to check if ans is int
   cout<<ans<<"n";
   else 
   cout<<"-1"<<"n";
}
return 0;
}
long double m;
long double value = sqrt(m);
if(floor(value) == (value)) {
    cout << "Sqrt of given number is integer n";
}

还有一个小建议。在 14 行的编程中 ans=pow(m,1.0/n); .使用 powl() 而不是 pow,因为变量的类型为 long double

编辑:正如Potatoswatter在此答案的评论部分中所建议的那样,C++过载pow()因此无需详细说明powl()

#include <iostream>
#include <cmath> 
using namespace std;
int main() {
    long double m; // No need to assign zero
    long double n,ans; // No need to assign zero
    int t;
    cin >> t;
    for(int i = 0; i < t; i++) {
        cin >> n >> m;
        ans = powl(m,(1.0/n));
        if(floor(ans) == ans)//this is to check if ans is int
            cout << ans <<"n";
        else 
            cout << "-1" << "n";
    }
    return 0;
}