Find the error in each of the following program segments and explain how to correct it:

```
a) float cube(float); // function prototype
cube(float number) { // function definition return number * number * number;
}
b) int randomNumber{srand()};
c) float y{123.45678};
int x;
x = y;
d) double square(double number) {
double number{0};
return number * number;
}
e) int sum(int n) {
if (0 == n) {
return 0;
}
else {
return n + sum(n);
}
}
```

a) Error: The function definition defaults to a return type of int.
Correction: Specify a return type of float for the function definition.
b) Error: Function srand takes an unsigned argument and does not return a value.
Correction: Use rand instead of srand. cout << static_cast(x) << endl;
c) Error: The assignment of y to x truncates decimal places.
Correction: Declare x as type float instead of int and remove the now-redundant static_cast.
d) Error: Variable number is declared twice.
Correction: Remove the declaration of variable number within the {}.
e) Error: Infinite recursion.
Correction: Change sum(n) to sum(n - 1).

Computer Science & Information Technology

You might also like to view...

Every recursive method must have a base case.

What will be an ideal response?

Computer Science & Information Technology

What is displayed by the following code?

```System.out.print("Hi, ABC, good".matches("ABC ") + " "); System.out.println("Hi, ABC, good".matches(".*ABC.*"));``` a. false false b. true false c. true true d. false true

Computer Science & Information Technology