Hey all,
I found this program quite difficult to understand at first so I spent about 40 minutes breaking it down line by line and since a lot of people have said they found it difficult too, I’m posting the program with my own explanatory comments alongside. It isn’t perfect but might help someone else here.
[code]void metersToFeetAndInches(double meters, int *ftPtr, double *inPtr) {
//From main(), where this function gets called, 3.0 gets passed in as the value for meters, and then this function is supplied with locations (&feet and &inches) where the values for feet and inches can be stored. So the placeholders/parameters for these are inevitably pointers to an address.
//Convert meters to feet. 1 meter = 3.281 feet so we need a double.
double rawFeet = meters * 3.281; //variable 'rawFeet' would appear to be total feet (i.e. not broken down into inches). rawFeet has a value of 9.483ft.
int feet = (int)floor(rawFeet); //floor() is used to convert rawFeet into an integer stored in variable feet. Feet has a value of 9.
printf("Storing %d to the address %p\n", feet, ftPtr); //Store the number of feet at the supplied address
*ftPtr = feet; //stores that integer in *ftPtr
//Calculate inches
double fractionalFoot = rawFeet - feet; //floor() and subtraction are used to break rawFeet into its integer and fractional parts. floor() has taken rawFeet which was 9.843ft and provided us with the integer 9 which is our value for feet. So here fractionalFoot = 9.843ft - 9 = 0.843ft. Note: This 0.843 is still measured in feet.
double inches = fractionalFoot * 12.0; //inches = 0.843feet * 12.0 inches (as 1 foot = 12 inches). Inches evaluates to 10.1.
//Store the number of inches at the supplied address
printf("Storing %.2f to the address %p\n", inches, inPtr);
*inPtr = inches;
}
int main(int argc, const char * argv[]) {
double meters = 3.0;
int feet;
double inches;
metersToFeetAndInches(meters, &feet, &inches);
printf("%.1f meters is equal to %d feet and %.1f inches.", meters, feet, inches);
return 0;
}[/code]