简体   繁体   中英

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.

  • You are to write a program which will compute square roots to a desired degree of accuracy. Begin the program by prompting the user for two numbers: (1) the value for which to determine the square root and (2) the number of decimal places of accuracy desired in the result. Use loops that determine the next highest perfect square and the next lowest perfect square respectively. A count-controlled loop should then be constructed; it will execute once for each of the desired decimal positions;
  • During a single pass of this count-controlled loop, the approximation will be either incremented or decremented by Δ = 1 / 10decimalPosition until the actual value is passed. On the first pass of the loop, Δ will be 1 / 10 1 = 0.1; on the second pass, Δ will be 1 / 10 2 = 0.01, and so on. If the approximation is too small an event-controlled loop inside the count-controlled loop will increment the approximation until it becomes too big.

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.

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. 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.

Extra HINT:

There are two nested loops. Outer loops checks for step >= error and inner loops check that result will be small enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM