Hi coders,
I was trying this exercise but I don’t understand why give this error
addWithSurcharge(1, 1) does not return 4 , but 3 .
This is the exercise :
Write a function addWithSurcharge that adds two amounts with surcharge. For each amount less than or equal to 10 , the surcharge is 1 . For each amount greater than 10 , the surcharge is 2 . The call addWithSurcharge(5, 15) should return 23 .
In this line you are first checking if amount is less than/equal to 10 or greater than 10. That will always evaluate to true since every option is true. So now we have essentially: if ((true) && (amount2 <= 10 || amount2 > 10))
Same thing for amount2. It will always be either less than//equal to 10 or greater than 10. So now it’s: if ((true) && (true))
Of course that’s always true. So return surcharge + 1; will always follow.
For each amount less than or equal to 10 , the surcharge is 1 . For each amount greater than 10 , the surcharge is 2 . The call addWithSurcharge(5, 15) should return 23 .
How do you get 23 from 5 and 15? What is the surcharge value vs the sum of the two numbers? I think that this question should help you see the error in your logic.
In general, you want to keep you logic clean and simple. Get something that works correctly and is simple first. If you want, later you can go back and try to reduce the number of lines. But simplicity and readability improves maintainability and saves you time in the future.
A function that adds two amounts with surcharge. For each amount less than or equal to 10 , the surcharge is 1 . For each amount greater than 10 , the surcharge is 2 . The call addWithSurcharge(5, 15) should return 23 .
Using the example for a result of 23:
=> 5 is less than or equal to 10, so you have to add this amount with surcharge of 1 => 5 + 1 (a)
=> 15 is greater than 10, so you have to add this amount with surcharge of 2 = > 15 + 2 (b)
I’m trying to try to consolidate the basics, but I’ve been struggling for almost two years without having great results. I do little things, but sometimes they seem difficult.
It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.
We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.
You can post solutions that invite discussion (like asking how the solution works, or asking about certain parts of the solution). But please don’t just post your solution for the sake of sharing it.
If you post a full passing solution to a challenge and have questions about it, please surround it with [spoiler] and [/spoiler] tags on the line above and below your solution code.