This question already has answers here:
Integer division: How do you produce a double?

(11 个回答)


6年前关闭。




我正在划分两个 int 值,我希望得到一个双值。但它的工作原理很奇怪,它在除法之前具有正确的值,但没有给出正确的答案。
    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);
        }

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

-----------------出局-------------------- ---------
 Sent packets: 2694 , Received packets: 5753 , ratio: 0

最佳答案

(double)this.sentPackets/this.receivedPackets

...应该修复它。

关于java - java中的错误划分,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3553047/

10-10 06:13