✍️ Practice (Easy)
1. Mismatched Sum
The program below prints 24 instead of 6. Fix it so that it prints 6.
int num1 = 2;
string num2 = "4";
Console.WriteLine(num1 + num2);
👀Hint
What does + do when one of the values is a string?
💡Solution
One solution:
int num1 = 2;
int num2 = 4; // int, not string
Console.WriteLine(num1 + num2); // 6
Alternatively tho:
int num1 = 2;
string num2 = "4";
Console.WriteLine(num1 + int.Parse(num2)); // 6
2. Integer Division
The program below is supposed to print 0.5, but it prints 0. Fix it so that it prints 0.5.
double half = 1 / 2;
Console.WriteLine(half);
👀Hint
What type is the result when you divide two ints?
💡Solution
Dividing two ints gives an int, so 1 / 2 becomes 0.
double half = 1.0 / 2; // 1.0 is a double, so this is double / int = double
Console.WriteLine(half); // 0.5
Alternatively tho:
double half = (double)1 / 2; // cast happens first, then double / int = double
Console.WriteLine(half); // 0.5
3. Naming Things
The program below doesn't compile because of 3 invalid variable names. Rename them so that it runs.
int 1stPlace = 1;
string first name = "Elizabeth";
double total.cost = 20.95;
Console.WriteLine(1stPlace);
Console.WriteLine(first name);
Console.WriteLine(total.cost);
👀Hint
Check the rules for what a variable name can't start with or contain!
💡Solution
int firstPlace = 1; // can't start with a number
string firstName = "Elizabeth"; // can't contain a space, use camelCase
double totalCost = 20.95; // can't contain a period, use camelCase
Console.WriteLine(firstPlace);
Console.WriteLine(firstName);
Console.WriteLine(totalCost);
4. Tipping Point
What is the magic number in the program below? Rewrite the program so that it no longer has one.
double lunchTip = 20.00 * 0.15;
double dinnerTip = 60.00 * 0.15;
Console.WriteLine(lunchTip + dinnerTip);
👀Hint
If the tip rate changed to 18%, how many places would you need to update?
💡Solution
0.15 is the magic number. It appears twice, and nothing says it's a tip rate. Give it a name with const:
const double TipRate = 0.15; // constants are PascalCase
double lunchTip = 20.00 * TipRate;
double dinnerTip = 60.00 * TipRate;
double total = lunchTip + dinnerTip; // store calculations in a variable
Console.WriteLine(total);
Now changing the tip rate is a one-line edit.