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 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.
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))
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.
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.