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