给定范围内的完美平方:循环执行异常

Perfect squares in a given range: abnormal execution of loops

本文关键字:循环 执行 异常 范围内 完美      更新时间:2023-10-16

程序编号 1:在给定的 a 和 b 范围内,a<=b,我想找出一个数字是否是完美的 quare,如果是,则打印它的根。因此,我编写了以下代码:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
using namespace std;
float squaredroot(int n) {
float low = 0.0, mid;
float high = (float)n+1;
while ((high-low) > 0.00001) {
    mid = (low+high) / 2;
    if (mid*mid < n) {
        low = mid;
    }
    else {
        high = mid;
    }
}
return low;
}
int main() {
int a,b,i=0; cin>>a>>b;
float roo=0.0;
for(i=a;i<=b;i++){
roo=squaredroot(i);
    if(floor(roo)==roo){
        cout<<roo<<endl;
    }
}
return 0;
}

对于给定的输入1 5输出应2 。但是,上述程序没有打印任何值。


尽管如此,当我尝试使用与程序编号 1 相同的基本概念运行另一个程序时,如上所述,它被完美地执行了。以下程序的任务是检查输入是否为完全正方形。如果是,则打印数字的根,否则打印"不是一个完美的正方形!以下是程序编号 2 的代码:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
using namespace std;
float squaredroot(int n) {
float low = 0.0, mid;
float high = (float)n+1;
while ((high-low) > 0.00001) {
    mid = (low+high) / 2;
    if (mid*mid < n) {
        low = mid;
    }
    else {
        high = mid;
    }
}
return low;
}
int main() {
int a; cin>>a;
float roo=0.0;
roo=squaredroot(a);
if(floor(roo)==roo){
    cout<<roo<<endl;
}
else{
    cout<<"Not a perfect square!"<<endl;
}
return 0;
}

我无法在第一个程序中找到错误。请帮忙。

与其弄乱平方根函数,不如考虑一下:

  • 连续的正方形由随后的奇数分隔。
  • 添加一些整数非常快。此外,您每次都会跳过越来越多的数字。
  • 平方根带你到浮点。这会将问题保留在整数中,即它所属的位置。

因此,要优雅地解决问题,只需执行以下操作:

#include <iostream>
using std::cout;
void print_perfect_square( int start, int end ) {
    int x = 0, nthOdd = 1;
    while ( x <= end ) {
        if ( x >= start ) {
            cout << x << " is a square and its root is "
                << nthOdd - 1  << 'n';
        }
        x += 2*nthOdd - 1;
        ++nthOdd;
    }
}
int main() {
    // it should find 9 and 16
    print_perfect_square(6,17);
    cout << 'n';
    // it sholuld skip negatives
    print_perfect_square(-10,5);
    cout << 'n';
    // it should print 25,36...
    print_perfect_square(20,100);
    return 0;
}
<</div> div class="answers">

正如陀螺仪所说,问题是squaredroot(4)返回1.99999809,所以floor(roo)!=roo。解决此问题的一种方法是将条件(floor(roo)==roo)更改为 (fabs(roo - floor(roo+0.5)) < 0.00001) .请注意,我使用的是函数 squaredroot 中的相同0.00001