题解 | #自动贩售机2#
自动贩售机2
http://www.nowcoder.com/practice/298dec1c3dce45c881f3e53e02558828
- 将所投入的货币数目用最小单位(五毛钱)以寄存器cnt记录,由于测试用例最多出现3元,所以cnt的范围0~6,定义其大小[2:0]。
- 需注意 根据输出波形知道在输入货币的下一个时钟才会输出信号,而不是当前时钟。
- 每次找零后记得归零cnt。
`timescale 1ns/1ns
module seller2(
input wire clk ,
input wire rst ,
input wire d1 ,
input wire d2 ,
input wire sel ,
output reg out1,
output reg out2,
output reg out3
);
//*************code***********//
reg[2:0] cnt;
always@(posedge d1) cnt <= cnt + 1;
always@(posedge d2) cnt <= cnt + 2;
always@(negedge rst or posedge clk)begin
if(~rst)begin
cnt <= 0;
out1 <= 0;
out2 <= 0;
out3 <= 0;
end
else if(sel == 0)begin //饮料一
if(cnt >= 3)begin
out1 <= 1;
cnt <= 0;
out3 <= cnt - 3;
end
else begin
out1 <= 0;
out2 <= 0;
out3 <= 0;
end
end
else begin //饮料二
if(cnt >= 5)begin
out2 <= 1;
cnt <= 0;
out3 <= cnt - 5;
end
else begin
out1 <= 0;
out2 <= 0;
out3 <= 0;
end
end
end
//*************code***********//
endmodule