With some help I have managed to get the right answer to these questions but I want to get my head around the concepts (i.e. understanding why these codes are correct), as understanding is very important and not just memory of syntax.
The first question is You're given the result of 3 competitions (true = win) , the prize for the first is 1, second is 2, third is 3. Return the total prize amount (you can win any combination of prizes)
The answer is:
public static int GetTotalPrize(bool first, bool second, bool third)
{
var result = 0;
if (first)
{ result += 1; }
if (second)
{ result += 2; }
if (third)
{ result += 3; }
return result;
}
How does the program know that if you were to win, let's say, the first, second and third prizes, that the total is 6? Or if you were to win the first and third, the total is 4? In other words, how does the code above account for all possible combinations?
The second question is You're given the result of 3 competitions in one of which you've won (true = win). The prize for the first is 1, second is 2, third is 3. Return the prize amount.
My answer is:
public static int GetPrize(bool first, bool second, bool third)
{
if (first)
return 1;
if (second)
return 2;
if (third)
return 3;
return 0;
}
Without the "return 0;" part at the end, my code was shown as incorrect. Why? As the question states that I have won one of the prizes, so in other words, I am not leaving the competition empty-handed.
Thanks in advance
Aucun commentaire:
Enregistrer un commentaire