NUMBER REPRESENTATION EXERCISES READING ------- Notes for lecture 2. Kernighan and Ritchie, 1.2 SUPPLEMENTAL READING -------------------- Deitel and Deitel, 9.1-9.5, Appendix E EXERCISES --------- 1. Convert 7654 from octal to hexadecimal. 2. Convert 7654 from octal to decimal. 3. Convert 7654 from decimal to octal. 4. Convert 7654 from decimal to binary. 5. Write a program that reads a decimal integer and prints out its value in octal. 6. Write a program that reads an octal integer and prints out its value in decimal. 7. Write a program that reads in two floats and prints out their ratio, to two decimal places. 8. Write a program that reads in two integers and prints out their ratio, to four decimal places. 9. Type in the following program, compile it, and use it to compute the average of a few sequences of five integers. #include main() { int i, sum, num; sum = 0; for (i = 0; i < 5; i++) { scanf("%d", &num); sum += num; } printf("%6.2f\n", sum/5.0); } . . . ANSWERS TO NUMBER REPRESENTATION EXERCISES 1. First convert to binary: 7654 = 111 110 101 100 = 1111 1010 1100 = FAC 2. 7*8^3 + 6*8^2 + 5*8 + 4 = 7*512 + 6*64 + 40 + 4 = 4012 3. 7654 decimal is 16746 octal 8^4 = 4096 7654 - 1*4096 = 3558 8^3 = 512 3558 - 6*512 = 486 8^2 = 64 486 - 7*64 = 38 8^1 = 8 38 - 4*8 = 6 8^0 = 1 6 - 6*1 = 0 4. Shortcut: convert the octal from exercise 3 to binary (see exercise 1). 1110111100110 5. #include main() { int n; scanf("%d", &n); printf("%o\n", n); } 6. #include main() { int n; scanf("%o", &n); printf("%d\n", n); } 7. #include main() { float x, y; scanf("%f %f", &x, &y); printf("%6.2f\n", x/y); } 8. #include main() { int x, y; scanf("%d %d", &x, &y); printf("%8.4f\n", x/(float) y); } Note: "(float) x/y" doesn't work because the integer division happens before the float cast. 9. % cc avg0.c % a.out 1 2 3 4 5 3.00 % a.out 123 456 789 876 543 557.40