Solution for Exercise 20-2

ex2002

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main()
{
    float *temperature;
    int c;

    /* allocate memory */
    temperature = (float *)malloc(sizeof(float)*1);
    if(temperature == NULL)
    {
        puts("Unable to allocate memory");
        exit(1);
    }
    
    /* prompt for input */
    printf("What is the temperature? ");
    scanf("%f",temperature);
    getchar();                /* swallow the newline */
    printf("Is this value (C)elsius or (F)ahrenheit? ");
    c = toupper(getchar());

    /* evaluate input */
    if(c=='F')
    {
        printf("%.2f Fahrenheit is ",*temperature);
        *temperature = (*temperature + 459.67) * (5.0/9.0);
        printf("%.2f Kelvin\n",*temperature);
    }
    else if(c=='C')
    {
        printf("%.2f Celsius is ",*temperature);
        *temperature += 273.15;
        printf("%.2f Kelvin\n",*temperature);
    }
    else
        puts("Invalid response");

    return(0);
}

Output

What is the temperature? 100
Is this value (C)elsius or (F)ahrenheit? f
100.00 Fahrenheit is 310.93 Kelvin

Notes

* Line 7 declares the float pointer temperature. This pointer is assigned a memory location by the malloc() function at Line 11. See how malloc() is typecast? Plus, the argument uses the sizeof operator to determine the exact amount of storage needed for one float variable.

* Lines 12 through 16 deal with a memory allocation error.

* The temperature variable is assigned a value by scanf() at Line 20. No & is needed because temperature is a pointer variable.

* Line 21 is required to consume the newline generated by scanf() at Line 17. Remember: Standard input is stream-oriented, not interactive. If the newline isn't swallowed here, the getchar() function at Line 23 would read the Enter key press in response to the second prompt (printf() at Line 22).

* The if-else if-else structure handles the temperature math based on input.

* Peeker notation, *temperature is required for the output as the program needs the value stored at address temperature, not the address itself.