cast.c

/*
 * demonstrate order of precedence with cast and division
 *
 * Matt Bishop, ECS 36A
 * April 4, 2024	original version
 */
#include 

int main(void)
{
	double f1 = 4.6;	/* chosen so division into 9.75 is 2 */
	double f2 = 9.75;	/* but into 9 is 1                   */
	double f3;		/* result of diivision as doubles */
	double f4, f5, f6;

	/* first, the exact answer */
	f3 = f2 / f1;

	/* now what we want to see -- does the cast refer to */
	/* f2 or the quotient f2/f1?			     */
	f4 = (int) f2 / f1;

	/* the value if the cast binds to f2 (we force the binding) */
	f5 = ((int) f2) / f1;

	/* the value if the cast binds to f2/f1 (we force the binding) */
	f6 = (int) (f2/f1);

	/* print the possibilities */
	printf("The value of the division result is: %f\n", f3);
	printf("The value of (int) f2/f1 is: %f\n", f4);
	printf("If (int) binds to the numerator f2, the result is: %f\n", f5);
	printf("If (int) binds to the division f2/f1, the result is: %f\n", f6);

	/* now print the answer */
	if (f4 == f5)
		printf("***** (int) binds to the numerator f2 *****\n");
	if (f4 == f6)
		printf("***** (int) binds to the division f2/f1 *****\n");
	return(0);
}

UC Davis sigil
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email: mabishop@ucdavis.edu
ECS 36A, Programming & Problem Solving
Version of April 4, 2024 at 12:13PM

You can get the raw source code here.

Valid HTML 4.01 Transitional Built with BBEdit Built on a Macintosh