modelsim使用function和display

【步骤1】在modelsim中输入<tryfactl.v>文件内容如下

module tryfact;
function[31:0]factorial;   //此处定义函数,[31:0]是返回值的类型或范围,factorial是函数名
  input[3:0]operand;        //端口说明语句
  reg[3:0]index;           //变量类型说明语句
begin
  factorial =1;
  for(index=2;index<=operand;index=index+1)
  factorial=index*factorial; //结果返回给函数名factorial
end
endfunction       //函数结束


//函数测试代码
reg[31:0]result;
reg[3:0]n;
initial begin
  result=1;
  for(n=2;n<=9;n=n+1) begin
     $display("partial result n= %d result=%d",n,result);
     result=n*factorial(n)/((n*2)+1);
  end
      $display("Finalresult=%d",result);
end
endmodule

【步骤2】在transcript窗口中输入vlog tryfact.v     // 编译源文件

编译成功后输入 vsim tryfact   //仿真tryfact模块

最后输入run -all    //运行仿真后就可以看到$display显示的结果

# partial result n= 2 result= 1
# partial result n= 3 result= 0
# partial result n= 4 result= 2
# partial result n= 5 result= 10
# partial result n= 6 result= 54
# partial result n= 7 result= 332
# partial result n= 8 result= 2352
# partial result n= 9 result= 18974
# Finalresult= 171890

原文地址:https://www.cnblogs.com/zhangxiujun/p/3750459.html