A.3. Chapter 3
A.3.1. Exercise 1 solution
Use the proper man page requests that appear in the following table. Note that printf overlaps with a command-line function, so you must specifically request the section for C functions. The section is optional for the other man pages.
Function | Man Page |
---|---|
printf | "3 printf" |
scanf | "scanf" or "3 scanf" |
pow | "pow" or "3 pow" |
A.3.2. Exercise 2 solution
Change the instances of int in Calculate.h to double. This includes
double calculate(const double a, const double b, const char op);
Change the instances of int in Calculate.c to double. This includes:
double calculate(const double a, const double b, const char op) { double result;
Replace the main function in main.c with the following code:
int main (int argc, const char * argv[]) { int count; double a, b, answer; char op; // print the prompt printf("Enter an expression: "); // get the expression count = scanf("%lg %c %lg", &a, &op, &b); if (count != 3) { printf("bad expression\n"); exit(1); } // perform the computation answer = calculate(a, b, op); // print the answer printf("%lg %c %lg = %lg\n", a, op, b, answer); return 0; }
A.3.3. Exercise 3 solution
Add the following include after the other includes in Calculate.c:
#include <math.h>
Add the following case entries to the switch statement. Here is the final switch statement:
case '/': result = a / b; break; case '\\': result = (int)a / (int)b; break; case '%': result = (int)a % (int)b; break; case '^': result = pow(a, b); break;
Your Calculate.c file ...
Get Beginning Mac OS® X Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.