c++ - C++ 阶乘函数返回 inf
问题描述
所以我正在编写一个 C++ 程序,该程序旨在获取一个数字的因数,但是当我将一个大数字传递给它时,它以“inf”返回,我试图添加一个 if 语句来检查它是否更大比数据类型的最大大小,是一个长双精度,这不能解决这个问题。有人可以帮忙吗?谢谢。这是我的代码:
long double factoral(long double num)
{
if (num >= std::numeric_limits<long double>::max() || num < std::numeric_limits<long double>::min())
{
return 0;
}
if (num > 1)
{
return num * factoral(num - 1);
}
else
{
return 1;
}
}
int main()
{
long double res = factoral(1000);
if (res == 0)
{
std::cout << "The factoral of 1000 is either too large or too small";
}
else
{
std::cout << "The factoral of 1000: " << res;
}
}
解决方案
inf
您的结果在 ( ) 处溢出,return num * factoral(num - 1);
因此您只需检查附近的限制,如下所示。
long double factoral(long double num) {
if (num > 1) {
long double ret = num * factoral(num - 1);
if (ret >= std::numeric_limits<long double>::max())
return 0;
return ret;
}
return 1;
}
我还建议您使用类似(未经测试的代码)的迭代解决方案
long long fac(long long num) {
long long ret = 1;
while (num--) ret *= num; //< handle limits here
return ret;
}
推荐阅读
- excel - Laravel 导出到 excel - 下载问题
- html - 将多个 HTML 文件导入 Excel 中的一张工作表
- google-cloud-platform - 限制 GCP 数据流?
- python - 从 github 安装 OpenAI Gym 环境
- css - 为什么我的 CSS 媒体查询没有根据我的条件做出响应?
- r - 我可以使用什么命令来删除重复值?
- java - Kotlin 公共常量在其他 Java 类中不可访问?
- swift - 如何快速使用 UIImagePickerController.InfoKey.editedImage 真正编辑图像?
- c++ - 从 char16_t(utf16) 到 utf8 的转换在 Visual Studio 2015 和 2017 中不起作用
- swiftui - 在 SwiftUI 中为 TextField 设置初始值 - 比较新旧值