How to Do Floating Point Divisions
- 1). Load the C++ IDE by clicking on its program icon. When it opens, select "File/New/Project" and choose "C++ Project" to create a new C++ project. A blank source code file appears in the text editor portion of the IDE.
- 2). Write the following code to declare a function named "divide."
double divide_floats(float x, float y)
{
} - 3). Write a statement that checks to see if you are dividing-by-zero. Suppose the "y" variable from the function declaration made in the last step is the divisor. Write the following "if" statement in-between the curly brackets of the function "divide_floats."
if(y == 0)
{cerr << "Divide by zero error << endl;} - 4). Write the logic that occurs when the "if" statement evaluates as false. That is, when the divisor is not zero. Write the following "else" statement below the "if" statement:
else
{} - 5). Write the code that divides the two floating point numbers. Since the resulting number might be larger than either of the two numbers being divided, if it was stored in a floating point data type there might be a loss of precision error. This occurs when the result exceeds what the data type is capable of storing, and therefore the results are corrupted. You can work around this by using a similar data type to the "float" called the "double," which uses twice the memory of a "float." Write the following in the curly brackets after the "else" statement:
double result = x / y; - 6). Write the following statement to return the answer from the function:
return result; - 7). Declare a main function. This is where your program starts execution and it is where you can call the function "divide_floats." Write the following:
int main()
{} - 8). Call the "divide_floats" function and output its value to the output window by writing the following statement in-between the curly brackets of the main function:
cout << divide_floats(5,2) << endl; - 9). Run the program by pressing the green "Play" button. The program launches and divides two floats. The program output is "2.5."
Source...