我有作业要交,但我的循环有问题。我首先必须通过我已经可以做到的循环找到下一个最高和最低的平方根。接下来我的作业告诉我,我需要通过平均整数的下一个最高和最低平方根来获得平方根的近似值。然后我必须向用户询问他们想要的精度的小数位数。这是作业中的引述:
A count-controlled loop should then be constructed; it will execute once for each of the desired decimal positions; in the example, this loop will execute four times (once each for the tenths, hundredths, thousandths, and ten-thousandths decimal positions). Use a counter such as decimalPosition to keep track of which pass the loop is on.
这是我遇到问题的地方,我正在根据用户输入的小数位数使用 while 循环,但我的循环没有完成循环。我是编程新手,所以如果这真的很简单,请原谅我。这是我的 while 代码:
for (int decimalPosition = 1; decimalPosition <= decimal; decimalPosition++)
{
while (baseRoot*baseRoot > num)
{
baseRoot = baseRoot - (pow((.1),decimalPosition));
cout << fixed << setprecision(decimal) << baseRoot << endl;
}
}
这是我到目前为止的输出
Enter a number you wish to know the square root of: 8
Enter the number of decimal places of accuracy you want: 7
Find the square root of 8 to 7 decimal places:
2.6000000
2.7000000
2.8000000
2.9000000
2.9000000 square root of 8.0000000
最佳答案
它叫做 Newton's method ,它的收敛是二次的。这应该可以帮助您弄明白。
PS - 巴比伦人首先发现了它,但牛顿因此获得了荣誉。
关于c++ - 在 C++ 中通过迭代求平方根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12486959/