?前言:
????????該題為睿思芯科筆試題,筆試時長20分鐘。
題目描述
????????用代碼實(shí)現(xiàn)斐波那契數(shù)列,代碼需要對對enable敏感,當(dāng)enable為高幾周期,sum在enble為高的下一周期輸出第幾個斐波那契數(shù),斐波那契數(shù)列的生成是后一個數(shù)字是前兩個數(shù)字之和,如下序列:0、1、1、2、3、5、8、13、21、34...,當(dāng)enable為0時,輸出端口sum的值為0
? ? ? ? 另外,當(dāng)enable拉高第一周期時,在下一拍輸出0,拉高第n個周期,在下一拍輸出第n個斐波那契值。
tips:斐波那契數(shù)列F(0)=1,這里的F(0)=0是因?yàn)楣P試題就是這樣出的,筆者僅是復(fù)述題目并實(shí)現(xiàn),重點(diǎn)在于實(shí)現(xiàn)思路。
解題思路
? ? ? ? 解題的方法就是利用斐波那契數(shù)列的特性,用兩個寄存器存儲斐波那契數(shù)列的值,然后在下一周期通過非阻塞賦值更新reg1和reg2的值,并且把二者之和輸出給sum。
reg_sum<= reg1+reg2;
reg1 <= reg2;
reg2 <= reg1+reg2;
? ? ? ? 還有一個要點(diǎn),題目要求?enable為0時,sum輸出0,所以由于enble和輸出的sum是錯了一拍的,為了讓他們對齊,需要對enble打一拍得到enable_dl。然后根據(jù)enable_dl是否為1,確定輸出應(yīng)該為斐波那契值還是0.文章來源:http://www.zghlxwxcb.cn/news/detail-642198.html
代碼
module fib_gen(
input clk, // positive edge trigger clock
input rstn,// active low reset
input enable,
output [31:0] sum
);
reg [31:0] reg1,reg2,reg_sum;
reg [31:0] counter;
reg enable_dl;
always @(posedge clk)begin
if(!rstn)begin
reg1 <= 32'd0;
reg2 <= 32'd1;
reg_sum <= 32'd0;
end
else if(enable )begin
if(counter==32'd0)begin
reg_sum <= 32'd0;
end
else if(counter == 32'd1)begin
reg1 <= 32'd0;
reg2 <= 32'd1;
reg_sum <= 32'd1;
end
else begin
reg_sum<= reg1+reg2;
reg1 <= reg2;
reg2 <= reg1+reg2;
end
end
end
always @(posedge clk)begin
if(!rstn)
counter <= 32'd0;
else if(enable)begin
counter <= counter + 1'b1;
end
end
always @(posedge clk)begin
if(!rstn)
enable_dl<= 1'd0;
else
enable_dl <= enable;
end
assign sum = enable_dl ? reg_sum:0;
endmodule
testbench
module tb();
reg clk, rstn,enable;
wire [31:0 ]sum;
initial begin
forever #5 clk = ~clk;
end
initial begin
rstn = 1'b0;
clk = 1'b1;
enable = #1 1'b0;
#10
rstn = #1 1'b1;
#10
enable = #1 1'b1;
#100
$finish();
end
fibonacci u_fibonacci(
.clk (clk ),
.rstn (rstn ),
.enable (enable ),
.sum (sum )
);
initial begin
$fsdbDumpfile("fibonacci.fsdb");
$fsdbDumpvars(0);
end
endmodule
波形?
文章來源地址http://www.zghlxwxcb.cn/news/detail-642198.html
到了這里,關(guān)于斐波那契數(shù)列verilog實(shí)現(xiàn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!