Lab 03 - Assert
Thanks for my Lab Tutor Zhang Puyu!
Slides:
Exercise 1 Review
Code Style
Initialize the variable immediately after the declaration.
For example,
// Not Recommended
double num;
num = cs1010_read_double();
// Recommended
double num = cs1010_read_double();
Do not declare the function and then implement it somewhere else (Usually after
main()
). Implement your function right after the declaration.
No return after else
Code Example
// Not allowed
if (something)
{
return something;
}
else
{
return other_things;
}
Out of succient reasons, the else
is of no use. So, we can simplify the code to below
// Allowed
if (something)
{
return something;
}
return other_things;
No nested If
If your code is like below
if (something_1)
{
if (something_2)
{
// do something
}
}
Since there is only one if
statement inside the "outer" if
, so there is no need to use the nested if
. And we can simplify it into
if (something_1 && something_2)
{
// do sommething
}
Assert Library
assert.h
is a library designed to help with debugging procedures.
Usage
assert(p)
where p
is a boolean expression. When the condition p
fails during program execution, the program will halt with an error message.
Exercise 1 Further Discussion
odd.c
A solution that uses no condition is that , where is the smallest odd number that is strictly bigger than .
The Deriving process

multiple.c
Modulo is not defined when we divide a non-zero number by 0. That is , where , is not defined!!!
date.c
There is a method not using conditions. Map each date to the integer .
power.c
Ways to optimize
Remove the useless work, when the base is 0, -1 or 1.
long compute_power(long x, long y)
{
if (x == 0)
{
return 0;
}
if (x == 1)
{
return 1;
}
if (x == -1)
{
return y % 2 == 0 ? 1 : -1;
}
// ...
}
Half the calculation
Recall that
Then convert it to code will be intuitive
if (y % 2 == 0)
{
return compute_power(x * x, y / 2);
}
return x * compute_power(x * x, (y - 1) / 2);
taxi.c
A normal way to compute ceil()
long ceil_of_quotient(long n, long m)
{
if (n % m == 0)
{
return n / m;
}
return n / m + 1;
}
A smart way to compute ceil()
Suppose we want to calculate , where and are two possitive integers. First, let us write , where and . Now, let's consider
If , then we will get as the output. If , then the above numerator is at least but strictly less than , so the quotient evaluates to , which will be our output.
Thus, convert the result into `C` code ```c long ceil_of_quotient(long n, long m) { return (n + m - 1) / m; } ```
Last updated