Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/156.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 查找区间内所有数字的第n个根_C++_Visual C++ - Fatal编程技术网

C++ 查找区间内所有数字的第n个根

C++ 查找区间内所有数字的第n个根,c++,visual-c++,C++,Visual C++,我有一个程序,它必须在一个区间内打印所有整数的完美平方根。现在我想为n根做这个 这是我所做的,但我被困在fmod #include <iostream> #include <math.h> using namespace std; int nroot(int, int); int main() { int p, min, max,i; double q; cout << "enter min and max of the int

我有一个程序,它必须在一个区间内打印所有整数的完美平方根。现在我想为n根做这个

这是我所做的,但我被困在fmod

#include <iostream>
#include <math.h>
using namespace std;

int nroot(int, int);

int main()
{

    int p, min, max,i;
    double q;

    cout << "enter min and max of the interval \n";
    cin >> min;
    cin >> max;
    cout << "\n Enter the n-th root \n";
    cin >> p;
    i = min;

    while (i <= max)
    {
        if (fmod((nroot(i, p)), 1.0) == 0)
        {
            cout << nroot(i, p);
        }
        i++;
    }
    return 0;
}

int nroot (int i, int p){

    float q;
    q = (pow(i, (1.0 / p)));

    return q;
}
#包括
#包括
使用名称空间std;
int-nroot(int,int);
int main()
{
int p,min,max,i;
双q;
cout>min;
cin>>最大值;
cout>p;
i=最小值;

而(i您可能希望以相反的方向处理此问题。与其取区间中每个值的第n个根来查看第n个根是否为整数,不如取区间边界的第n个根,并根据根进行步进:

// Assume 'min' and 'max' set as above in your original program.
// Assume 'p' holds which root we're taking (ie. p = 3 means cube root)
int min_root = int( floor( pow( min, 1. / p ) ) );
int max_root = int( ceil ( pow( max, 1. / p ) ) );

for (int root = min_root; root <= max_root; root++)
{
    int raised = int( pow( root, p ) );
    if (raised >= min && raised <= max)
        cout << root << endl;
}

如果您真的关心性能(我怀疑您在本例中不是这样),您可以替换
int(pow(…,p))
使用完全用整数算法计算n次方的代码。但这似乎有些过分。

浮点数的精确相等测试可能不会像您预期的那样工作。最好与一些较小的数字进行比较:

float t = nroot(i, p);
if (fabs(t - rintf(t)) <= 0.00000001)
{
  cout << t << endl;
}
float t=nroot(i,p);

如果(fabs(t-rintf(t))你被困在fmod是什么意思?我的意思是我想用fmod作为%10来比较nroot()使用.Like测试一个数字是否为偶数。很棒的idea。并且它只使用整数。谢谢。这是一个非常好的通用点,不能重复足够多的时间。它似乎会让所有使用浮点运算的人都感到困惑。在我上面的示例中,我重述了这个问题,以避免完全进行浮点相等比较,原因类似:浮点相等比较很糟糕。
float t = nroot(i, p);
if (fabs(t - rintf(t)) <= 0.00000001)
{
  cout << t << endl;
}