Verilog阶乘器

Verilog实现的阶乘功能。

module FactorialFunc(clk,reset_low,ans,n);
  input clk,reset_low;
  input[3:0] n;
  output reg[31:0] ans;
  
  always @(posedge clk)
  begin
    if(!reset_low)
      ans = 0;
    else
      begin
        ans = factorial(n);
      end
  end
  
  function[31:0] factorial;
    input[3:0] total;
    reg[3:0] index;
    
    begin
      factorial = total ? 1:0;
      for(index = 2; index <= total; index = index+1)//TODO: index <= total(CS162), error. don't know why.
      begin
        factorial = factorial * index;
      end
    end
  endfunction
endmodule

测试代码如下:

`timescale 1ns/1ns
`include "FactorialFunc.v"

module FactorialFunc_Test;
  reg clk,reset;
  wire[31:0] ans;
  reg[3:0] n,i;
  
  initial
  begin
    clk = 0;
    reset = 1;
    n = 0;
    
    forever #50 clk = ~clk;
  end
  
  initial
  begin
    //#100 reset = 0;
    //#100 reset = 1;
    for(i = 0;i < 15; i = i + 1)//TODO: n?1
    begin
      n = i;
      @(negedge clk)
      $display($time," n=%d,ans=%d",n,ans);
    end
    $stop;
  end
  
  FactorialFunc u1factorialfunc(.clk(clk),.reset_low(reset),.ans(ans),.n(n));
endmodule


你可能感兴趣的:(Verilog,HDL,Verilog,阶乘)