1.1 KiB
1.1 KiB
- The following function, which computes the area of a triangle, contains two errors. Locate the errors and show how to fix them. (Hint: There are no errors in the formula)
double triangle_area(double base, height)
double product;
{
product = base * height;
return product / 2;
}
Answer:
// A type annotation is needed for `height`
double triangle_area(double base, double height)
{
// The `product` variable declaration was not in the function block.
double product;
product = base * height;
return product / 2;
}
- Write a function
check(x, y, n)
that returns1
if bothx
andy
fall between zero andn - 1
inclusive. The function should return 0 otherwise. Assume thatx
,y
, andn
are all of type int
int check(int x, int y, int n) {
int in_range = 1;
if (x < 0 || y < 0) {
in_range = 0;
}
if (x > n - 1 || y > n - 1) {
in_range = 0;
}
return in_range;
}
- Suppose that function
f
has the following definition:int f(int a, int b) { ... }
Which of the following statements are legal? Assume thati
has typeint
andx
has typedouble
).