Anonymous Anonymous - 9 months ago 36
C Question

C Primer Plus Programming Exercise Question

I'm working through 'C Primer Plus', was just going through the programming exercises and I've hit a brick wall on the last one on the fifth chapter (Operators, Expressions and Statements).

The exercise is:

Write a program that requests the user to enter a Fahrenheit temperature. The program should read the temperature as a type double number and pass it as an argument to a user-supplied function called Temperatures(). This function should calculate the Celsius equivalent and the Kelvin equivalent and display all three temperatures with a precision of two places to the right of the decimal. It should identify each value with the temperature scale it represents. Here is the formula for converting Fahrenheit to Celsius:

Celsius = 1.8 * Fahrenheit + 32.0

The Kelvin scale, commonly used in science, is a scale in which 0 represents absolute zero, the lower limit to possible temperatures. Here is the formula for converting Celsius to Kelvin:

Kelvin = Celsius + 273.16

The Temperatures() function should use const to create symbolic representations of the three constants that appear in the conversions. The main() function should use a loop to allow the user to enter temperatures repeatedly, stopping when a q or other nonnumeric value is entered.

My code is:

#include <stdio.h>
void Temperatures(double);
int main(void)
{
double farh;
printf("Enter a fahrenheit temperature: ");
scanf("%f", &farh);
printf("\n");
Temperatures(farh);
return 0;

}

void Temperatures(double f)
{

float c;
float k;
c = 1.8 * f + 32;
k = c + 273.16;
printf("Fahrenheit Celcius Kelvin\n");
printf("%.2f %.2f %.2f\n", f, c, k);

}


Where have I gone wrong? :o Just get nonsense.

Answer Source

You ask for a float %f as input through scanf but store it in a double. float and double is often of different size, and if so, you'll get garbage when trying to store a float inside a double. Try to use %lf instead, or change "farh" to float.