![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/457413761636191.png "=600 #left")
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
float e(float x);
float x;
cout << "请输入x" << endl;
cin >> x;
float sinh;
sinh = (e(x) - e(-x)) / 2;
cout << sinh;
return 0;
}
float e(float x)
{
int fac(int x);
float s;
float m;
int n;
s = 1;
for (n = 1; n <= 1000; n++)
{
m = x / fac(n);
s = s + m;
x *= x;
}
return s;
}
int fac(int x)
{ int s = 1;
if (x == 0)
return s;
else
{
for (; x >= 1; x--)
s *= x;
return s;
}
}
为什么下面的代码跑出的结果不对
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- Soda Wang 2021-11-06 14:18关注
中间溢出了。int只能存下12的阶乘,double只能存下170的阶乘。换个算法吧。
#include <iostream> #include <limits> double factorial(int n) { double ret = 1; bool int_fl = false; for (int i = 1; i <= n; i++) { ret *= i; if (ret > std::numeric_limits<int>::max() && !int_fl) { std::cout << "max factorial that int can store: " << i-1 << "\n"; int_fl = true; } if (ret > std::numeric_limits<double>::max()) { std::cout << "max factorial that double can store: " << i-1 << "\n"; break; } } return ret; } int main() { int imax = std::numeric_limits<int>::max(); std::cout << imax << '\n'; double dmax = std::numeric_limits<double>::max(); std::cout << dmax << '\n'; std::cout << factorial(1000) << '\n'; return 0; }
结果:
2147483647 1.79769e+308 max factorial that int can store: 12 max factorial that double can store: 170 inf PS D:\src\cpp_back_to_basics> py -c 'import math; print(math.factorial(13)>2147483647)' True PS D:\src\cpp_back_to_basics> py -c 'import math; print(math.factorial(171)>1.79769e+308)' True
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥20 测距传感器数据手册i2c
- ¥15 RPA正常跑,cmd输入cookies跑不出来
- ¥15 求帮我调试一下freefem代码
- ¥15 matlab代码解决,怎么运行
- ¥15 R语言Rstudio突然无法启动
- ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
- ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
- ¥15 用windows做服务的同志有吗
- ¥60 求一个简单的网页(标签-安全|关键词-上传)
- ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法