-2

I don't know why if I have the following code:

int main() {
    long int height_cat, number_worker_cats, number_helper_cats, height_tree;
    bool flag;
    scanf("%ld%ld", &height_cat, &number_worker_cats);
    for (number_helper_cats = 1; ; ++number_helper_cats) {
        for (height_tree = 1; (long int)pow(number_helper_cats + 1, height_tree) <= height_cat; ++height_tree) {
            if ((long int)(pow(number_helper_cats + 1, height_tree) - height_cat) == 0 && (long int)(pow(number_helper_cats, height_tree) - number_worker_cats) == 0) {
                flag = true;
                break;
            }
        }
        if (flag) {
            break;
        }
    }
 printf("%ld, %ld\n", number_helper_cats, height_tree);
}

I'm searching for number_helper_cats and height_tree which (number_helper_cats +1)^height_tree = height_cat and number_helper_cats^height_tree = number_worker_cats where height_cat and number_worker_cats are integers.

For example if height_cat = 216 and number_worker_cats = 125, the code will stop on number_helper_cats = 5 and height_tree = 3 since (5+1)^3 = 216 and 5^3 = 125.

But if I have the following code it doesnt work, loops forever, why?

int main() {
    long int height_cat, number_worker_cats, number_helper_cats, height_tree;
    bool flag;
    scanf("%ld%ld", &height_cat, &number_worker_cats);
    for (number_helper_cats = 1; ; ++number_helper_cats) {
        for (height_tree = 1; pow(number_helper_cats + 1, height_tree) <= height_cat; ++height_tree) {
            if ((long int)(pow(number_helper_cats + 1, height_tree)) == height_cat &&
                        (long int)(pow(number_helper_cats, height_tree)) == number_worker_cats) {
                flag = true;
                break;
            }
        }
        if (flag) {
            break;
        }
    }
printf("%ld, %ld\n", number_helper_cats, height_tree);
}

Everything is long int and every height_cat and number_worker_cats for testcase are true for the operations, another example height_cat = 5764801, number_worker_cats = 1679616, number_helper_cats = 6 and height_tree = 8 because (6 + 1)^8 = 5764801, 6^8 = 1679616. But again the first code runs well, and the second one loops forever. pow are precise I mean 6^3 = 216 and 5^3 = 125 right? :p

4

1 回答 1

1

的结果powdouble,并且double在很多情况下,数字并不精确。要测试与 a 的相等性double,一种常用方法是

if (abs(pow(number_helper_cats + 1, height_tree) - height_cat)) < 0.001); // 0.001 is an arbitrary small number
{
     ...
}

Aand 用于测试<=,您应该使用pow(number_helper_cats + 1, height_tree) <= height_cat + 0.001.

但是,我必须提到,您的代码无法使用我的 gcc 4.7.2 产生您在问题中提到的无限循环。您所有的循环都正常结束。

于 2012-11-15T15:48:47.593 回答