阶乘计算的可综合verilog代码-FPGA常见问题社区-FPGA CPLD-ChipDebug

阶乘计算的可综合verilog代码

 

根据输入的选择数和数字(最大为5),输出数字的立方、平方或者阶乘,

代码如下

module mux2_1
(
    input   wire        sys_clk,
    input   wire        sys_rst_n,
    input   wire [1:0]  select,
    input   wire [2:0]  num,        //输入的最大数为5
    
    output reg [6:0]    result
);
 
always@ (posedge sys_clk or negedge sys_rst_n)
    if(!sys_rst_n)
        result <= 7'd0;
    else
        case(select)
            2'b00: result <= num * num * num;   //立方
            2'b01: result <= num * num;     //平方
            2'b10: result <= factorial(num);    //阶乘
            default:result <= 7'd0;
        endcase
 
function [6:0] factorial;
    input [2:0] n;
    reg [2:0] index; 
    begin
        factorial = 7'd1;
        index = 3'd1;
        if(n == 3'd0 || n == 3'd1)
            factorial = 7'd1;
        else
            while(n != index ) begin
                index = index + 1;
                factorial = factorial * index;
            end
    end
endfunction
 
endmodule

 

测试代码testbench

`timescale  1ns/1ns
module tb_mux2_1();
reg sys_clk;
reg sys_rst_n;
reg [1:0] select;
reg [2:0] num;
 
wire [6:0] result; 
 
 
initial
    begin
        sys_clk <= 1'b0;
        sys_rst_n <= 1'b0;
        #20
        sys_rst_n <= 1'b1;
    end
 
always #10 sys_clk <= ~sys_clk;
 
always @(posedge sys_clk)
    begin
        select <= {$random} % 4;
        num <= {$random} % 6;
    end
    
mux2_1 mux2_1_inst
(
    .sys_clk         (sys_clk),
    .sys_rst_n       (sys_rst_n),
    .select          (select),
    .num             (num),        //输入最大数为5
                    
    .result          (result)
);
 
endmodule

 

波形调试

图片[1]-阶乘计算的可综合verilog代码-FPGA常见问题社区-FPGA CPLD-ChipDebug

输出延迟一个时钟

请登录后发表评论

    没有回复内容