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

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

概述计划编号1: 在给定范围a和b中,a< = b,我想找出一个数是否是一个完美的quare,如果是,则打印它的根.因此,我写了以下代码: #include <cmath>#include <cstdio>#include <vector>#include <iostream>using namespace std;float squaredroot(int n) {float low = 计划编号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;}
总结

以上是内存溢出为你收集整理的c – 给定范围内的完美正方形:循环的异常执行全部内容,希望文章能够帮你解决c – 给定范围内的完美正方形:循环的异常执行所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1257008.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存