简体   繁体   English

用于计算数字平方根的程序。

[英]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. 例如-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: 假设number为5,则我们有:

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

The same thing applies with the % 1 . % 1同样适用。 ints are always whole numbers, so modding by 1 always returns 0. int始终是整数,因此乘以1总是返回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. 这里的问题是使用正确的算法,这就是您需要在std库中的squareRootFinder函数中使用cmath标头。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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