In my book the question is "Write a function that takes two unsigned short integers and returns the result of dividing the 1st argument by the second. Do not perform the division if the second number is zero, but do return -1".
Two problems, I have managed to do it by showing an error message when the second number is zero but when I try to do it like the book wants I can't return -1 and I get a "floating point exception (core dumped)" message. Please help.
Do not perform the division if the second number is zero
Let me rename the variables in your function:
1 2 3 4 5 6 7 8 9
USHORT div( USHORT first, USHORT second )
{
if ( first == 0) { // this is what you wrote. Does it look right?
return -1;
}
else {
return ( first / second );
}
}
Second, does anything in the question say that the result has to be an USHORT?
#include <iostream>
// quotient of integer division:
// an unsigned integer initialised with a value of -1
// will be interpreted as a positive value. so make the return type
// a signed integer type which can hold (without loss of information)
// all the possible values that an unsigned short can hold.
// we assumes that that type is int (in practice, this is always true)
// returns -1 if the dividend is zero
int iquotient( unsignedshort divisor, unsignedshort dividend ) ;
// floating point division
// returns -1 (instead of +inf) if the dividend is zero
double divide( unsignedshort divisor, unsignedshort dividend ) ;
int main()
{
std::cout << iquotient( 270, 25 ) << ' ' << divide( 270, 25 ) << '\n' // 10 10.8
<< iquotient( 260, 0 ) << ' ' << divide( 270, 0 ) << '\n' ; // -1 -1
}
int iquotient( unsignedshort divisor, unsignedshort dividend )
{
return dividend == 0 ? -1 : divisor/dividend ;
}
double divide( unsignedshort divisor, unsignedshort dividend )
{
return dividend == 0 ? -1 : double(divisor)/dividend ;
}