繁体   English   中英

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

[英]Program that calculates square roots of a number.

我必须编写一个程序,该程序需要一个数字并输出其平方根。 例如-45->3√5。 我编写了一个程序,但是它只返回我输入的相同数字。非常感谢您的帮助。 这是我的代码->

#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;
}

这行的两个问题都与整数类型有关:

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

记住整数运算的结果是整数,函数中的第一组值是什么? 假设number为5,则我们有:

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

% 1同样适用。 int始终是整数,因此乘以1总是返回0。

这里的问题是使用正确的算法,这就是您需要在std库中的squareRootFinder函数中使用cmath标头。 您也可以使用函数来获取整数。 这是我的代码。 希望能帮助到你。

#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