Fixing Functions
This task is a text based task. You do not need to write any program/C++ file: the answer should be written in main.md (and might include code fragments if questions ask for them).
Task:
What are the problems (if any) with the following functions? Fix them and find appropriate pre- and postconditions.
- function is_even:
bool is_even(int i) {
if (i % 2 == 0) return true;
}
-
function invert:
double invert(int x) { double result; if (x != 0) { result = 1.0 / x; } return result; }
Hint: The C++ compiler does not protect you from certain types of errors. Therefore, even if you run a program in Code Expert, it is not guaranteed that the behaviour you observe is the “real” one. We have prepared a programming tracing handout that shows how to execute a program with a pen and paper and which conditions indicate bugs in the executed program not caught by the C++ compiler.
Solution
Please write your solution here.
For your convenience we have added a template for your answers below.
Note: Remember to also describe the problem of the function.
# Function `c++|is_even`:
The problem with this function is that it does not return a bool if the number `i` is uneven.
```c++
// PRE: n/a
// POST: returns true if i is even. If not it returns false.
bool is_even(int i) {
if (i % 2 == 0) return true;
else return false;
}
```
# Function `c++|invert`:
The problem with this function is
```c++
// PRE: x is positive or negative but not zero.
// POST: returns inverse with respect to multiplication of x.
double invert(int x) {
// TODO: Fix code below.
if (x != 0) {
return 1.0 / x;
}
else
std::cout << "0 has no inverse!";
}
```
Made by JirR02 in Switzerland 🇨🇭