程序拒绝产生结果是否导致无法进入循环?
请查看以下代码以获取更多信息。
#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;
}
答案 0 :(得分: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;
}
我希望它会对你有所帮助。