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

6 c++ algorithm loops

程序编号1:在给定范围ab中,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;
}
Run Code Online (Sandbox Code Playgroud)

对于给定的输入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;
}
Run Code Online (Sandbox Code Playgroud)

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

Adi*_*vin 2

正如 Gyro Gearloose 所说,问题在于squaredroot(4)返回1.99999809,因此floor(roo)!=roo。解决此问题的一种方法是将条件更改(floor(roo)==roo)(fabs(roo - floor(roo+0.5)) < 0.00001)。请注意,我使用的是0.00001function 中的相同内容squaredroot