Incorrect separation in java

I separate the two int values ​​and I expect to get double. but it works very strange, it has the correct values ​​before division, but it does not give the correct answer.

    public void Analyse() {
        for (FlowPacket fp : this.flow.GetAll()) {
            if (fp.direction==1){
               this.sentPackets++;
               this.sentLength = this.sentLength + fp.packetLength;
            }
            else{
                this.receivedPackets++;
                this.receivedLength = this.receivedLength + fp.packetLength;
            }

        }
        if(this.receivedPackets==0)
                this.receivedPackets = 1;
    }


public double CalcRatio() {
            return (this.sentPackets/this.receivedPackets);
        }

---------------------------- Basic ------------------ --- -----------

System.out.print("Sent packets: " + analyser.getTotalSentPackets() + " , ");
System.out.print("Received packets: " + analyser.getTotalReceivedPackets() + " , ");
System.out.print("ratio: " + analyser.CalcRatio() + " , ");

---------------------------- Outout ------------------ --- ---------

 Sent packets: 2694 , Received packets: 5753 , ratio: 0
+3
source share
6 answers
(double)this.sentPackets/this.receivedPackets

... must fix it.

+4
source

Dividing by double integer division (rounding down) is performed. Pass one of the integers to double division BEFORE so that double division occurs.

+4
source

Pass at least one of the int values ​​before (double)before division.

+2
source

When dividing int by int, the answer will be int. Therefore, he can cut off any residue that may be in the answer. To get a double answer, you have to make one of the ints double.

+2
source

Need to use for double ...

public double CalcRatio() {
            return ( (double) this.sentPackets/ (double) this.receivedPackets);
       }
+1
source

This is not only Java-specific behavior. It also works in .NET.

0
source

Source: https://habr.com/ru/post/1761222/


All Articles