1

I made a program that is able to compare 3 inputs for them to get the largest value (F) The problem is I cannot get the expected output of the problem. Expectation:

A      B      C      F
001(1) 111(9) 100(4) 111(9)
001(1) 001(1)  001(1) 000 

Actual Output:

My Output

module InputComparator(A,B,C,F);
input [2:0]A;
input [2:0]B;
input [2:0]C;
output reg [2:0]F;

    always @* begin
        if (A>B>C) begin   
            F = A;
            end
        else if (A>B<C) begin 
            F = B;
            end
        else if (A<B<C) begin 
            F = C;
            end
        else begin
            F = 3'b000; 
        end
end
endmodule

module testbench;
reg [2:0] A;
reg [2:0] B; 
reg [2:0] C; 

wire [2:0]F; 


InputComparator test(A,B,C,F);


initial
begin


$display("--------------------------------------------------------");
$display("3 Input Comparator");
$display("--------------------------------------------------------");
$display("Time\tA\tB\tC\tF");
$display("--------------------------------------------------------");
$monitor("%g\t%b\t%b\t%b\t%b",$time,A,B,C,F);


    A=3'b000; B=3'b000; C=3'b000;
#1  A=3'b101; B=3'b101; C=3'b101;
#1  A=3'b001; B=3'b111; C=3'b100;
#1  A=3'b110; B=3'b001; C=3'b101;
#1  A=3'b001; B=3'b100; C=3'b101;
#1$display("--------------------------------------------------------");

#1$display("--------------------------------------------------------");
#9 $finish;
end
endmodule

toolic
  • 57,801
  • 17
  • 75
  • 117

1 Answers1

2

You should not try to chain comparison operators like that: A>B>C. That does not do what you think it does, and it is a common pitfall (see explanation below). You must separate each comparison:

module InputComparator(A,B,C,F);
input [2:0]A;
input [2:0]B;
input [2:0]C;
output reg [2:0]F;

    always @* begin
        if ((A>B) && (A>C)) begin   
            F = A;
            end
        else if ((B>A) && (B>C)) begin 
            F = B;
            end
        else if ((C>A) && (C>B)) begin 
            F = C;
            end
        else begin
            F = 3'b000; 
        end
end
endmodule

I get this correct output:

--------------------------------------------------------
3 Input Comparator
--------------------------------------------------------
Time    A   B   C   F
--------------------------------------------------------
0   000 000 000 000
1   101 101 101 000
2   001 111 100 111
3   110 001 101 110
4   001 100 101 101
--------------------------------------------------------
--------------------------------------------------------

Verilog interprets (A>B>C) as ( (A>B) > C ). It evaluates (A>B) first, which resolves to either 0 or 1. Let's assume it resolves to 1. Thus, we are left with (1 > C), which is clearly not what you intended.

toolic
  • 57,801
  • 17
  • 75
  • 117