c++ - 计算数字平方根的程序。

标签 c++

我必须编写一个程序,它接收一个数字并输出它的平方根。例如 - 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。整数始终是整数,因此以 1 为模数总是返回 0。

关于c++ - 计算数字平方根的程序。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10150427/

相关文章:

c++ - 是否可以在 C++ 20 中为概念完成删除关键字模板?

c# - C++ 位图到 C# 位图

c++ - 类构造函数上的调用错误没有匹配函数

c++ - 模板的模板推导失败(中间有继承),有更好的方法吗?

c++ - 如何在 <T> 容器上使用 std::sample 返回指针 <T*> 的容器?

c++ - 通过在 C++ 中表示类名的字符串创建新对象

c++ - 是否允许在一个类中混合使用新旧 C++ 函数语法?

c++ - 函数的多重声明 make 命令 UNIX

c++ - 如何制作不接受浮点值的整数验证函数?

c++ - main() 中带有枚举的 typedef 结构不起作用