逻辑错误?潜水2 int导致浮动

时间:2017-02-06 06:41:10

标签: java floating-point precision floating-accuracy

我正在写一个战斗模拟器。我的攻击者类发起攻击,我的防御者类应该阻止它。 manager是我的主要类,用于计算和打印结果。我的问题是我的highRatio,mediumRatio和lowRatio变量。如果它们不等于1,则所有它们都设置为零。关于可能会发生什么的任何想法?

//后卫班

public int defenseSelector(int highAtkCounter, int mediumAtkCounter, int lowAtkCounter, int rounds, int roundCounter)
{
    Random defenseTypeGenerator;
    int defense = 0;
    float highRatio;
    float mediumRatio;
    float lowRatio;

    defenseTypeGenerator = new Random();
    int defenseType = defenseTypeGenerator.nextInt(MAX_ROUNDS) + 1;

    highRatio = highAtkCounter/roundCounter;
    mediumRatio = mediumAtkCounter/roundCounter;
    lowRatio = lowAtkCounter/roundCounter;



   if(roundCounter > 3 && roundCounter <= rounds) //AI portion
   {
       if (highRatio > mediumRatio && highRatio > lowRatio)
       {
            defense = HIGH;
       }

       else if (mediumRatio > highRatio && mediumRatio > lowRatio)
       {
            defense = MEDIUM;
       }

       else if (lowRatio > highRatio && lowRatio > mediumRatio)
       {
            defense = LOW;
       }

       else
       {
            System.out.println("AI ERROR ratios " + highRatio + " " + mediumRatio + " " + lowRatio);
            System.out.println("AI ERROR atkCounters " + highAtkCounter + " " + mediumAtkCounter + " " + lowAtkCounter);
            System.out.println("AI ERROR rCounters " + roundCounter);

//经理类

while(roundCounter <= rounds)
    {
        int attack = theAttacker.attackSelector(high, medium, low);

        int highAtkTracker = theAttacker.countHighAtks(attack);
        System.out.println("DEBUG " + attack);
        System.out.println("DEBUG " + highAtkTracker);
        int mediumAtkTracker = theAttacker.countMediumAtks(attack);
        System.out.println("DEBUG " + attack);
        System.out.println("DEBUG " + mediumAtkTracker);
        int lowAtkTracker = theAttacker.countLowAtks(attack);
        System.out.println("DEBUG " + attack);
        System.out.println("DEBUG " + lowAtkTracker);

        highAtkCounter = highAtkCounter + highAtkTracker;
        mediumAtkCounter = mediumAtkCounter + mediumAtkTracker;
        lowAtkCounter = lowAtkCounter + lowAtkTracker;


        int defense = theDefender.defenseSelector(highAtkCounter, mediumAtkCounter, lowAtkCounter, rounds, roundCounter);

1 个答案:

答案 0 :(得分:0)

在java中,任何带整数的算术运算都会产生整数。

因此,必须明确地将整数转换为浮点类型:

    highAtkCounter = highAtkCounter + (float)highAtkTracker;
    mediumAtkCounter = mediumAtkCounter + (float)mediumAtkTracker;
    lowAtkCounter = lowAtkCounter + (float)lowAtkTracker;