简体   繁体   中英

Program that calculates square roots of a number.

I have to make a program, which takes in a number and outputs the square root of it. Ex - 45 --> 3√5. I made a program, but it just returns the same number that i put in. Help would be greatly appreciated. Here's my code -->

#include<iostream>
using namespace std;


int squarerootfinder(int number, int divisor){
     if(divisor == 1){

            return 1;
     }
     else{

            if((number / (divisor * divisor))% 1 != 0){

                    divisor = squarerootfinder(number, divisor - 1);

            }
            if((number/ (divisor * divisor)) % 1 == 0 ){
            return divisor;

            }

      }

}
int main(){
     int number;
     cout << "Enter a number to find the square root of it \n";
     cin >> number;
     int divisor = number;
     int squareroot;
     squareroot = squarerootfinder(number, divisor);
     cout << squareroot << endl;
     return 0;
}

Two problems with this line both related to the integer type:

if((number / (divisor * divisor))% 1 != 0){

Remembering that the result of an integer operation is an integer, what is the value of the first set of values that go into the function? Assume number is 5. Then we have:

5/(5*5) = 5/25 = 0

The same thing applies with the % 1 . ints are always whole numbers, so modding by 1 always returns 0.

The issue here is to use the right algorithm, and that is you needed to use the cmath header in std library, in your squareRootFinder function. You can also use a function to get your integer. Here is my code. Hope it helps.

#include <iostream>
#include <cstring>
#include <cmath>


using namespace std;

int getPositiveInt(string rqstNum)
    {
        int num;
        do
        {
           cout << rqstNum << endl;
           cin >> num;
        }while(num == 0);

        return num;
    }


double squareRootFinder(double Num)
    {
        double squareroot;
        squareroot = sqrt(Num);
        return squareroot;
    }

int main()
{
 int Num = getPositiveInt("Enter a number and i'll calculate the squareroot ");
 double squareroot = squareRootFinder(Num);

    // To dispay the answer to two decimal places we cast the squareroot variable
    squareroot *= 100;
    squareroot = (double)((int)squareroot);
    squareroot /= 100;
    cout << squareroot << endl;

   return 0;
}

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