Functions that Return
A function can return a value. You've been doing this for weeks already.
Example 1. Reading Lines
Console.ReadLine() takes no arguments and returns a string:
string userInput = Console.ReadLine();
Example 2. Ice Cream Costs Money
Ice cream costs $3.50 plus $2.00 per scoop. Update GetIceCream so it:
- Takes the number of scoops, the flavour, and the amount paid.
- Serves the ice cream if the customer paid enough, and returns their change.
- Prints a message and returns their money if they didn't pay enough.
static double GetIceCream(int scoops, string flavour, double payment)
{
double price = 3.50 + 2.00 * scoops;
if (payment < price)
{
Console.WriteLine($"lol That costs ${price} tho");
return payment; // exit the function early (rejection)
}
Console.WriteLine($"Here is {scoops} scoop(s) of {flavour} 🍦");
return payment - price;
}
Example 3. Get Positive Double
This function keeps asking until the user enters a positive number:
static double GetPositiveDouble()
{
Console.Write("Enter a positive double: ");
double num = double.Parse(Console.ReadLine());
while (num < 0)
{
Console.Write("Enter a POSITIVE double plz: ");
num = double.Parse(Console.ReadLine());
}
return num;
}