Trap 8 - Divide

◀ Trap 7 - Factorial▶ Programming Exercises
Amazon The following program is supposed to receive two integers from the user and output the result of dividing the first one by the second one. However, it does not work properly. Point out where things go wrong.
#include<iostream>
using namespace std;

int divide(int dividend, int divisor) {
	int result;
	result = dividend / divisor;
	return result;
}
int main(){
	int a, b, c;
	cout<<"Enter first integer: ";
cin>>a; cout<<"Enter second integer: "; cin>>b; c = divide(a, b); cout<<a<<" divided by "<<b<<" is "<<c<<endl; return 0; }

Solution
You should be able to point out that the result of the division is always an int, which means that it is inaccurate if it is supposed to be a floating-point number. Another bug is that when user enters 0 as the second integer, the program yields a segmentation fault.

This is a small program and most of you probably see this bug already, but it demonstrates an important point I mentioned earlier - preconditions of a function must be preserved.
In divide(), a precondition should be that the divisor must not be 0. However, we have no control over the user’s inputs, so in order to preserve this precondition, we need to make sure that the divisor is not 0 before we do the division.

One way is to use an if statement to see if the divisor is 0; if so, simply output an error message and terminate the program.


Another way is to use try-catch blocks to handle that exception. Whatever you do, see to it that preconditions of a function are always preserved.

Next let’s get our feet wet in some of the most interesting programming exercises! Once you go through them you’ll see the power of the four step programming model in Chapter 11.8!

Diamonds are merely carbon in its most concentrated form.
◀ Trap 7 - Factorial▶ Programming Exercises

fShare
Questions? Let me know!