c++ - 为什么我的代码在阶乘返回垃圾值中查找尾随零的数量

标签 c++ math factorial

我想找出阶乘中尾随零的数量,但我的代码返回的是垃圾值。

#include<iostream>
using namespace std;

int main()
{   
   long int n;
   cin>>n;
   int z=0;
   while(n>0)
   {
      n=n/5;
      n=z+n;
      z=n;
   }
   return z;
}

最佳答案

我理解你的代码如下:你的输入是 n 并且你想计算 n! 有多少个尾随零。在这种情况下,您的 while 循环必须如下所示:

while(n > 0)
{
    n = n / 5;
    z = z + n;
}

// After running the loop, directly output the result.
cout << "z: " << z;

这在 1000 的扩展中给了我 249 个尾随零! 4617 有 1151 个尾随零!

根据 this page那应该是正确的。

关于c++ - 为什么我的代码在阶乘返回垃圾值中查找尾随零的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31775255/

相关文章:

algorithm - 如何计算数组中的最大中位数

matlab - Zoidberg曲线,无法到达 "zoidberg"的解决方法

c - 安西C : factorial function wrong a

c++ - 在函数内部创建局部 vector ,然后将其作为引用传递给其他将其存储为引用的函数

c++ - 为什么这会在 const 方法中返回一个 const X* const 指针?

haskell - Haskell 是否有某种数字转换为科学格式?

c++ - 谁能解释这个计算大阶乘的算法?

C++:尝试在单个 for 循环中使用 getlline() 填充多个 vector 时, vector 下标超出范围

c++ - 当方法体在头文件中时是否强制内联?

c - 在 C 中打印出从 (0 到 n) 的阶乘列表