6.47 (Find the Error) Find the error in each of the following program segments a
ID: 3731583 • Letter: 6
Question
6.47(Find the Error) 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;
cout << static_cast < float >( x ) << endl;
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 );
}
Explanation / Answer
float cube( float ); // function prototype
a)
float cube( float ); // function prototype
cube( float number ) // function definition
Correction :
function defintion must include which type of data it retuturns.
Here it returns the float value, so include the float in the function definition.
correct function definition:
float cube( float number ) // function definition
b)
int randomNumber = srand();
correction srand() is not correct change srand() to rand(), because srand() takes only unsigned arguments.
correct declaration:
int randomNumber = rand();
c)
float y = 123.45678;
int x;
x = y;
cout << static_cast < float >( x ) << endl;
correction :
declare int x as float x so it will assign the value of y to the value of x without any loss of point value
Here no need to use of static_cast < float.
correct program:
float y = 123.45678;
float x;
x = y;
cout << x << endl;
d)
double square( double number )
{
double number = 0; // Here number is declared twice so remove double here
return number * number;
}
Correct program:
double square( double number )
{
number = 0;
return number * number;
}
e)
Correct program:
int sum( int n )
{
if ( 0 == n )
return 0;
else
return n + sum( n ); // Every time n value is not changed so it goes to infinite recursion
}
replace sum( n ) to sum( n -1 )
int sum( int n )
{
if ( 0 == n )
return 0;
else
return n + sum( n - 1);
}
Please rate my Aneswer
Thank you
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.