【问题标题】:Babylonian Algorithm with C++ unable to get loop to run带有 C++ 的巴比伦算法无法让循环运行
【发布时间】:2016-02-08 06:33:42
【问题描述】:

程序拒绝产生结果是因为它无法进入循环吗?

请查看以下代码以获取更多信息。

#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

int main()
{
    double x, squareroot, oldsquareroot, counter=0;
    cout << "Enter a positive number: " ;
    cin >> x ;
    {
        for (oldsquareroot = x/2; abs(squareroot-oldsquareroot) >= 1e-9 &&   abs(squareroot - oldsquareroot)>=(1E-8*x);counter++ )
        {
             squareroot = (squareroot+x/squareroot)/2;
        }

    }
    cout << setprecision(15);
    cout << "The value of the squareroot is:" << squareroot << endl;
    cout << "The number of interations required for the computation is:" <<  counter << endl;
    return 0;


}

【问题讨论】:

  • 描述你得到的输出,即什么都没有,不是你期望的等等。另外,使用调试器检查是否进入了循环。您不需要整个社区来检查程序执行情况。附带说明:比较双精度值,尤其是这样的小值,对于条件表达式来说是一个非常糟糕的主意。

标签: c++ algorithm for-loop math numerical-methods


【解决方案1】:

有一些错误。 现在它工作正常。

#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

int main()
{
    double x, squareroot, oldsquareroot, counter = 0;
    cout << "Enter a positive number: ";
    cin >> x;
    {
        squareroot = x; // fixed error 1: using of uninitialized variable.
        for (oldsquareroot = x / 2; abs(squareroot - oldsquareroot) >=  1e-9 && abs(squareroot - oldsquareroot) >= (1E-8*x); counter++)
        {
            oldsquareroot = squareroot;// fixed eror 2: oldsquareroot is not changed in the loop and can't exit.
            squareroot = (squareroot + x / squareroot) / 2;
        }
    }
    cout << setprecision(15);
    cout << "The value of the squareroot is:" << squareroot << endl;
    cout << "The number of interations required for the computation is:" << counter << endl;
    return 0;
}

希望对你有帮助。

【讨论】:

  • 我不赞成,因为它会影响其他人的家装,并且不能以任何方式解释错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-13
  • 1970-01-01
  • 1970-01-01
  • 2012-06-03
  • 1970-01-01
  • 2020-04-19
  • 2020-05-12
相关资源
最近更新 更多