4

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
Red Lion
  • 213
  • 3
  • 10
  • 18

6 Answers6

4
(double)this.sentPackets/this.receivedPackets

... should fix it.

xagyg
  • 9,562
  • 2
  • 32
  • 29
4

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.

Jeffrey
  • 1,681
  • 3
  • 13
  • 23
3

When dividing an int by an int the answer will be an int. Therefor it will cut off any remainder there may be in the answer. In order to get a double answer you must cast one of the ints to a double.

Jeff
  • 103
  • 6
2

Cast at least one of the ints to (double) before dividing.

dan04
  • 87,747
  • 23
  • 163
  • 198
1

Need to cast to double...

public double CalcRatio() {
            return ( (double) this.sentPackets/ (double) this.receivedPackets);
       }
zevra0
  • 271
  • 1
  • 5
0

It is not only Java-specific behaviour. It works the same way in .NET, too.

Petr Kozelek
  • 1,126
  • 8
  • 14