2010-08-24 63 views
3

我將兩個int值分開,並且希望得到一個double值。但它很奇怪,它在分割之前有正確的值,但它沒有給出正確的答案。java中的錯誤劃分

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 

回答

4
(double)this.sentPackets/this.receivedPackets 

...應該修復它。

2

將至少一個整數投射到(double)在劃分之前。

4

分割的結果被轉換爲double AFTER整數除法(舍入)。在分割之前將其中一個整數轉換爲double,以便發生雙重分割。

1

需要轉換翻一番......

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

當將一個int由一個int答案是一個整數。因此,它將切斷答案中可能存在的任何剩餘部分。 爲了得到雙重答案,您必須將其中一個整數轉換爲雙精度。

0

它不僅是Java特有的行爲。它在.NET中也以相同的方式工作。