[英]C++ Finding square roots to a precision
This is my first time using C++ and I have the homework assignment as follows, with an attempt below it. 这是我第一次使用C ++,我的作业分配如下,并在下面进行尝试。
I am unsure as how to start constructing the loops for the process in paragraph 2. Despite the instructions they don't make sense to me. 我不确定如何开始为第2段中的过程构建循环。尽管有指示,但它们对我来说没有意义。
My progress so far: 到目前为止,我的进度:
int
sqroot()
{
cout << setiosflags (ios::fixed|ios::showpoint); //assumed I need for output later
double number;
cout<<"Enter the number to find the square root of: ";
cin>>number;
int sqRoot = 1;
while (sqRoot*sqRoot < number) // sqRoot is too small
sqRoot++; // try the next number
int y=0;
int newRoot =1;
while (y < number)
{
if (newRoot*newRoot > number )
break;
y=newRoot*newRoot;
newRoot++;
}
int decimalInput;
int decimalPosition= 0;
cout<<"Enter the desired decimal position: "<<endl;
cin>>decimalInput;
while (decimalPosition < decimalInput)
decimalPosition++;
return 0;
}
You should not just increment new newRoot by 1 (newRoot++), but by smaller steps. 您不仅应该将新的newRoot递增1(newRoot ++),而且应以较小的步长递增。 To make it more efficient, you start whit big step (big power of 10, for instance 1000) .Divide this step by 10 just before square of your result will be bigger than input number.
为了提高效率,您可以开始大步(10的幂次方,例如1000)。在结果的平方大于输入数之前,将该步除以10。
Extra HINT: 额外提示:
There are two nested loops. 有两个嵌套循环。 Outer loops checks for step >= error and inner loops check that result will be small enough.
外循环检查步骤> =错误,内循环检查结果是否足够小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.