简体   繁体   中英

Can someone explain what is wrong with my code?

The tax depends on how far apart their salaries are. If the salaries are within $10,000 of each other, the tax is 5% of the total. If they are more than $10,000 apart, the tax is 5% of the larger income plus 3% of the smaller one. Can someone explain what I'm doing wrong with my if statements that isn't letting the test pass.


public double spouseDistance(double income1, double income2)
{
    double tax;
    double totalincome = income1 + income2;
    double incomedistance = income1 - income2;
    if (incomedistance > 10000)
    {
        if(income1 > income2)
        {
            tax = income1 * 0.05 + income2 * 0.03;
        }else
    {
        tax = income2 * 0.05 + income1 * 0.03;
    }
    }
        else
        {
            tax = totalincome * 0.05;
        }

    return tax;
}

}


@Test
public void testSpousesDistance()
{
    TaxCalculator tc = new TaxCalculator();
    // The border case here is when the difference between the
    // salaries is 10,000 and the value changes at 10,000.01.
    // Since the order of the parameters shouldn't matter, do
    // both cases with both parameter orders
    assertEquals(40000*0.05, tc.spouseDistance(25000,15000), 0.001);
    assertEquals(40000*0.05, tc.spouseDistance(15000,25000), 0.001);
    assertEquals(30000.01*0.05 + 20000*0.03,tc.spouseDistance(20000.00,30000.01), 0.001);
    assertEquals(30000.01*0.05 + 20000*0.03,tc.spouseDistance(30000.01, 20000.00), 0.001);
}

}

You want to set incomeDistance to Math.abs(income1 - income2) to get the absolute value of the difference. The way you have it, if income2 > income1 you branch to the wrong block of code.

Take your 20,000 and 30,000.01 example. At that point incomeDistance become 20,000-30,000.01, or -10,000, which is less than 10,000.

You have to make sure that the result of the incomedistance is not negative. Because if income 2 is greater than income one, in your code, the result will appear negative.

If the result is negative, multiply the result by (-1) if you don't want to include an entire library just for a single purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM