Solution for Exercise 16-2

ex1602

#include <stdio.h>

int main()
{
    int a,b;
    float c;

    printf("Input the first value: ");
    scanf("%d",&a);
    printf("Input the second value: ");
    scanf("%d",&b);
    c = (float)a/(float)b;
    printf("%d/%d = %.2f\n",a,b,c);
    return(0);
}

Notes

* Replacing the equation at Line 12 with something like (float)(a/b) wouldn't do the job. That's because integer a is still being divided by integer b and the result, even inside parentheses, remains an integer value. The (float) typecast merely takes that value, 1, and converts it into 1.0.

* You've already seen a typecast in use in the book, in Chapter 11. The srand() function example uses a typecast:

The typecast above is (unsigned). The value returned by the time() function is signed, yet srand() requires an unsigned value. The typecast fixes the warning that occurs as well as any burps in the output given that Lord-only-knows what would happen if srand() were fed a signed value.