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

C++ 给定范围内的完美正方形:循环的异常执行,c++,algorithm,loops,C++,Algorithm,Loops,程序编号1: 在给定的a和b范围内,a如Gyro Gearlose所说,问题是squaredoot(4)返回1.9999809,因此地板(roo)=roo。解决此问题的一种方法是将条件(floor(roo)=roo)更改为(fabs(roo-floor(roo+0.5)) SavaReSoOT ./P> < P>中使用了相同的 0.00001代码>。 连续的正方形由连续的奇数分隔 加上一些整数真是太快了。而且每次你都跳过越来越多的数字 平方根带你去浮动。这将问题保留在整数中,它属于整数 因此

程序编号1
在给定的a和b范围内,a如Gyro Gearlose所说,问题是
squaredoot(4)
返回
1.9999809
,因此
地板(roo)=roo
。解决此问题的一种方法是将条件
(floor(roo)=roo)
更改为
(fabs(roo-floor(roo+0.5))<0.00001)
。请注意,我从函数<代码> > SavaReSoOT ./P> < P>中使用了相同的<代码> 0.00001代码>。
  • 连续的正方形由连续的奇数分隔
  • 加上一些整数真是太快了。而且每次你都跳过越来越多的数字
  • 平方根带你去浮动。这将问题保留在整数中,它属于整数
因此,要优雅地解决您的问题,只需执行以下操作:

#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;
}
#包括
使用std::cout;
无效打印(整数开始,整数结束){
int x=0,n奇数=1;
while(x=开始){

如果你对整数感兴趣,为什么要使用float?float类型足够简单,可以接受一些舍入误差;但是在其他任何地方它都是麻烦。@Gyro gearlose可能有很多可能的方法来解决上述问题。但是问这个问题的主要目的是想知道为什么和/或如果程序1中的循环行为异常。P.S.相应地更改了问题标题。打字:您的意思是
squaredroot(4)
对于问题中提到的相同输入,建议修改后程序1的输出为
0.99992
2
。所需输出为2(应为整数)但是,问题是,如果程序2能够为
squaredroot(4)
打印
2
,那么为什么程序1不能这样做。要修复输出,请打印
floor(roo+0.5)
而不是打印
roo
。至于程序2,在我的机器上它也不能很好地工作。这可以很好地工作。但是,问题是程序1出了什么问题。错误一定在for循环中。@RaviKiran如果返回的平方根不太准确,则floor函数将与平方根不同,从而导致o错误地错过该输出。
#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;
}