加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 03:36:13 所属栏目:百科 来源:网络整理
导读:计划编号1: 在给定范围a和b中,a = b,我想找出一个数是否是一个完美的quare,如果是,则打印它的根.因此,我写了以下代码: #include cmath#include cstdio#include vector#include iostreamusing namespace std;float squaredroot(int n) {float low = 0.0,mid
计划编号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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读