Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wrong division in java [duplicate]

Tags:

java

I am dividing two int values, and im expecting to get a double one. but it works very strange, it has the correct values just before division but it doesnt give the right 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);
        }

----------------------------main--------------------------------

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
like image 241
Red Lion Avatar asked Dec 10 '22 14:12

Red Lion


2 Answers

(double)this.sentPackets/this.receivedPackets

... should fix it.

like image 53
xagyg Avatar answered Dec 12 '22 05:12

xagyg


The result of the division is cast to a double AFTER integer division (with rounding down) is performed. Cast one of the integers to a double BEFORE dividing so that double division occurs.

like image 43
Jeffrey Avatar answered Dec 12 '22 04:12

Jeffrey