八度的斐波那契数列

问题描述 投票:-1回答:1

我需要通过Octave中的函数运行斐波那契数列。

我获得了预期的输出,但是由于输出中的限制,我的测试用例失败。

 function fibo(n)
 a=0;
 b=1;
 x(:,1)=[1];
 for i=2:n
   c=a+b;
   x(:,i)=[c];
   a=b;
   b=c;
 endfor
 g=sprintf("%d   ",x);
 fprintf("Fibonacci sequence:   %s\n",g)
 endfunction    

 a = input("");
 fibo(a)

如果输入= 10,输出:(测试用例失败)

enter image description here

使用时

g=sprintf("\t%d",x);

正在显示以下输出:

enter image description here

任何人都可以通过解决缩进来帮助我通过测试用例!

algorithm matlab octave fibonacci
1个回答
2
投票

由于预期输出的图像不可突出显示,所以我不能百分百确定,但是看起来每个数字的固定宽度均为4个字符。

因此,我看到输出的方式是:

Fibonacci sequence: ---1 ---1 ---2 ---3 ---5 ---8 --13 --21 --34 --55

这里-表示填充空格。

要进行此更改,您的打印行应更改为以下内容:

g=sprintf(" %4d", x);
fprintf("Fibonacci sequence: %s\n", g)

Aside:该函数应为x预分配内存,以便更好地进行内存管理。在MATLAB中,这类似于:

a=0;
b=1;
x = zeros(1, n); % This reserves memory for n numbers
x(:,1)=[1];
... % your code below

此外,由于x被设计为一维数组,所以使用起来可能会更容易

x(i) = c

代替类似的东西>

x(:,i) = [c]

© www.soinside.com 2019 - 2024. All rights reserved.