gpt4 book ai didi

c++ - 给定范围内的完美正方形 : abnormal execution of loops

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:33:55 25 4
gpt4 key购买 nike

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

#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 相同的基本概念运行另一个程序时,即上面提到的,它执行得很完美。以下程序的任务是检查输入是否为完美正方形。如果是,则打印数字的根,否则打印“Not a perfect square!”。以下是程序编号 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;
}

我找不到第一个程序中的错误。请帮忙。

最佳答案

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

  • 连续的方 block 由连续的奇数分隔。
  • 添加一些整数的速度非常快。此外,您每次都会跳过越来越多的数字。
  • 平方根带你去漂浮。这将问题保留在它所属的整数中。

所以,为了优雅地解决你的问题,只需这样做:

#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++ - 给定范围内的完美正方形 : abnormal execution of loops,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35258357/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com