M-文件
fprintf('\n\nn!\n')
for i=[1:length(timearray)]
fprintf('%s \t %d \n', stringarray{i},factorial(timearray(i)))
end
Run Code Online (Sandbox Code Playgroud)
产量
n!
microsecond 1
minute Inf
hour Inf
day Inf
month Inf
year Inf
century Inf
Run Code Online (Sandbox Code Playgroud)
我正在尝试计算在n运行的算法的步数!采取上述间隔(假设1步= 1微秒).但是,我无法fprintf显示有意义的结果.
切换到fprintf('%s \t %bu \n', stringarray{i},factorial(timearray(i)))给了我一些数字,但我怀疑他们错了.
%bu输出
n!
microsecond 04607182418800017408
minute 09218868437227405312
hour 09218868437227405312
day 09218868437227405312
month 09218868437227405312
year 09218868437227405312
century 09218868437227405312
Run Code Online (Sandbox Code Playgroud)
免责声明:我写了这个程序来解决作业问题,但是家庭作业从未指定编写程序.
谢谢你的帮助!
麦克风
问题可能不在于打印本身,而在于因子计算本身就是溢出的.尝试仅评估值而不是在循环中打印它; 你会发现阶乘函数在170之后溢出!
避免这种情况的一种简单方法是返回log-factorial:
log_factorial = @(n) sum(log(1:n));
Run Code Online (Sandbox Code Playgroud)
然后,您可以比较不同规模的值,而不必担心溢出.注意:上面的函数没有矢量化,因此只能使用单个值输入; 如果您需要使用数组值,那么似乎已有其他解决方案可用.