给定范围内的完美平方:循环执行异常
Perfect squares in a given range: abnormal execution of loops
程序编号 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;
}
<</div>
div class="answers"> 正如陀螺仪所说,问题是squaredroot(4)
返回1.99999809
,所以floor(roo)!=roo
。解决此问题的一种方法是将条件(floor(roo)==roo)
更改为 (fabs(roo - floor(roo+0.5)) < 0.00001)
.请注意,我使用的是函数 squaredroot
中的相同0.00001
。
相关文章:
- 在映射擦除c++期间执行循环的次数
- C++-For循环未执行
- 如何强制循环执行另一次迭代到零并关闭循环
- 程序在循环执行后崩溃
- 如何使用两个 for 循环执行唯一的洗牌
- 对于循环执行失败,因为变量我不会递增,为什么?
- pi的倍数到千分之一的值可能会改变循环执行方式
- For 循环执行奇怪的增量跳转
- 在循环执行之间释放内存
- 如何计算循环执行了多少次?C++
- 给定范围内的完美平方:循环执行异常
- 需要澄清有关此循环执行乘法的信息
- 有条件的大平面数组遍历和令人惊讶的短循环执行时间
- c++openmp,用于循环执行期间的循环最大减少值
- 为什么循环执行时间的此C++存在显着差异?
- 对于循环条件内的循环执行,C++
- 使用for循环执行线程
- c++中While循环执行得太早
- c++中while循环执行中的打印输出语句
- 这个 while 循环执行其适当的功能,但对于其他内容是必需的