Find the error in each of the following program segments and explain how to correct it:
a) float cube( float ); // function prototype
int x;
x = y;
cout << static_cast< float >( x ) << endl;
{
double number;
return number * number;
}
{
if ( n == 0 )
return 0;
else
return n + sum( n );
}
a) float cube( float ); // function prototype
double cube( float number ) // function definition
{
return number * number * number;
}
{
return number * number * number;
}
ANS: The function definition defaults to a return type of int. Specify a return type of float for the definition.
b) register auto int x = 7;
ANS: Only one storage class specifier can be used. Either registeror auto must be removed.c) int randomNumber = srand();
ANS: Function srand takes an unsigned argument and does not return a value. Use rand instead of srand.d) float y = 123.45678;
int x;
x = y;
cout << static_cast< float >( x ) << endl;
ANS: The assignment of y to x truncates decimal places.e) double square( double number )
{
double number;
return number * number;
}
ANS: Variable number is declared twice. Remove the declaration within the {}.f) int sum( int n )
{
if ( n == 0 )
return 0;
else
return n + sum( n );
}
ANS: Infinite recursion. Change operator + to operator -.
Post A Comment:
0 comments: