The following is the C code for implementing the original version of density but does some error checking using decision statements.
/******************************************************
* *
* Brenda Sonderegger CS120 *
* *
* Class Example - Density of a Cube Aug. 30, 1998 *
* *
* Description: This program will calculate the density*
* of a cube given the length of one side in cm *
* and the mass of the cube in grams. *
* *
******************************************************/
#include <stdio.h>
#define EPSILON .001
int main(void)
{
float side, mass, density, volume;
printf("\n\n\nEnter the length of a side in centimeters ");
scanf("%f", &side);
/*NOTE the safe comparison for reals */
if (side < EPSILON)
printf("\nERROR - side can't be negative or zero - ending program.");
else
{
printf("\nEnter the mass of the cube in grams ");
scanf("%f", &mass);
if (mass < 0)
printf("\nERROR - mass can't be negative - ending program.");
else
{
volume = side * side * side;
density = mass/volume;
printf("\nFor a cube with side = %f and mass = %f, the density is %f\n",
side, mass, density);
printf("\n\n\n");
}
}
return (0);
}