我不知道为什么我有以下代码:
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);
}
我正在搜索number_helper_cats
和height_tree
(number_helper_cats +1)^height_tree = height_cat
和number_helper_cats^height_tree = number_worker_cats
,其中height_cat
和number_worker_cats
是integers
。
例如,如果height_cat = 216
和number_worker_cats = 125
,代码将从number_helper_cats = 5
和height_tree = 3
(5+1)^3 = 216
和5^3 = 125
停止。
但如果我有以下代码它不起作用,永远循环,为什么?
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);
}
一切都是long int
,每个height_cat和number_worker_cats for testcase都是true,另一个例子是height_cat = 5764801,number_worker_cats = 1679616,number_helper_cats = 6和height_tree = 8,因为(6 + 1)^ 8 = 5764801 ,6 ^ 8 = 1679616.但是第一个代码再次运行良好,第二个代码永远循环。 pow是精确的我的意思是6 ^ 3 = 216和5 ^ 3 = 125对吧? :P
答案 0 :(得分:1)
pow
的结果是double
,double
数字在很多情况下都不准确。要使用double
测试相等性,常见的方法是
if (abs(pow(number_helper_cats + 1, height_tree) - height_cat)) < 0.001); // 0.001 is an arbitrary small number
{
...
}
要测试<=
,请使用pow(number_helper_cats + 1, height_tree) <= height_cat + 0.001
。
但是,我必须提到你的代码不能用我的gcc 4.7.2产生你在问题中提到的无限循环。你的所有循环都正常结束。