Lesson 7 14 day challenge 4

what am I doing wrong??? im losing my head


**func** calculateTotalWithTax( subtotal:Double, tax:Double) -> Double{

**return** subtotal*tax

}

print (calculateTotalWithTax(subtotal: 5, tax: 5))

Help!

What is the output you get when you this code in the playground?
If it is 25 then the code is correct.

If however, you mean that there is a 5% tax for 5 dollars, Then you either pass in the tax as 1 + tax (1.05) or you modify the function to treat your tax as a percent, ie. Divide it by hundred then add the original value

func calculateTotalWithTax( subtotal:Double, tax:Double) -> Double{

    // Calculate the tax
    let requiredTax = subtotal * (tax/100)
    
    // Return the required tax plus the original amount
    return subtotal + requiredTax

}

print (calculateTotalWithTax(subtotal: 5, tax: 5))


Nothing comes out. No output and idk why? That’s why I am asking for help

Also how did you know to put it in this way?

There is a couple of things to consider when you are defining a function to calculates tax.

  1. if you want to tell the user to input the value as representing a percentage then the value should be a whole number. In this case it would be 5 as you did so in your original function call where you said.
print (calculateTotalWithTax(subtotal: 5, tax: 5))

Then in your function it would need to divide that by 100 like this:

func calculateTotalWithTax( subtotal: Double, tax: Double) -> Double {
    return subtotal * tax/100
}

BUT, that calculation only returns the amount of tax calculated on the subtotal. What you need to do is then add the subtotal to that calculation to return the total with tax like this:

func calculateTotalWithTax( subtotal: Double, tax: Double) -> Double {
    return (subtotal * tax/100) + subtotal
}

The alternative way is to do this:

func calculateTotalWithTax( subtotal: Double, tax: Double) -> Double {
    return subtotal * (1 + tax/100)
}

which is the same as multiplying the subtotal by 1.05.

To make it clear that the function requires a whole number to represent the tax amount you should name the tax parameter more clearly like this:

func calculateTotalWithTax( subtotal: Double, taxPercentage: Double) -> Double {
    return subtotal * (1 + tax/100)
}

The function call would be:

print (calculateTotalWithTax(subtotal: 5, taxPercentage: 5))

  1. If you wanted the user to input a decimal value to represent the tax amount then what you would do in your function is as follows:
func calculateTotalWithTax( subtotal: Double, tax: Double) -> Double {
    return subtotal * (1 + tax)
}

and your function call would be:

print (calculateTotalWithTax(subtotal: 5, tax: 0.05))

This may be a long winded explanation but I hope it helps. If there is anything that you are not clear on then by all means ask further questions.

1 Like

This is amazing! I need to study a bit more and if I have any Qs, which I will, ill get back to you. I guess I need to take a math class too.