# Celsius and Fahrenheit Converter

I'm very new to programming in C and I attempted to make a program that converts temperatures to and from Fahrenheit and Celsius. I have been running the program and I have realized that not all conversions are correct. For example, if I use the boiling point of water (100C or 212F), I get an incorrect answer. I thought that I used the correct formulas. I was wondering if you wouldn't mind reviewing this quick program.

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

int main(void) {

float c;
float f;
int w;

printf("Type 1 if you would like to convert to Farenheit\n");
printf("Type 2 if you would like to convert to Celcius\n");

scanf("%i", &w);

// Loop to make sure value is 1 or 2

while(w != 1 && w !=2) {

fprintf(stderr, "You didn't input a valid number. Please Try Again\n");
scanf("%i", &w);
}

// Celsius --> Fahrenheit
if(w == 1){
printf("Input the Celcius Temperature\n");
scanf("%f", &c);
printf("You entered %f\n", c);
f = c * (9./5.) + 32.;
printf("%f in Fareheit is %f\n", c, f);
}

// Fahrenheit --> Celsius
if(w == 2){
printf("Input the Farenheit Temperature\n");
scanf("%f", &f);
printf("You entered %f\n",f);
c = (f - 32.) * (5./9.);
printf("%f in Celcius is %f\n", f, c);
}

return 0;
}

• The problem is probably the integer division in 9/5 and 5/9. The result is 1 and 0, respectively, due to truncation to integer. Use 9./5 and 5./9, respectively. – janos Oct 29 '15 at 20:41
• Please update this in the posted code, otherwise it's technically "broken", and broken code is off-topic here: the code to review must fully work as intended – janos Oct 29 '15 at 20:52

1. Spelling "Celsius" (3 places)

printf("Type 2 if you would like to convert to Celcius\n");

2. Better to get return value of input functions (4 places). Even in learner code, it saves time during debug

// scanf("%i", &w)
int ret = scanf("%i", &w);
assert(ret == 1);

3. Infinite loop should user enter non-numeric input as the offending input is not consumed.

while(w != 1 && w !=2) {
fprintf(stderr, "You didn't input a valid number. Please Try Again\n");
// scanf("%i", &w);
ret = scanf("%i", &w);
assert(ret == 1);
}

4. Style: Suggest .0. Also since the input and output are float, code could use float constants. In general, unless floating point math is intensive or has larges array of data, recommend using double as that is C's default FP type.

// f = c * (9./5.) + 32.;
f = c * (9.0/5.0) + 32.0;
f = c * (9.0f/5.0f) + 32.0f;

5. Functional simplification: Rather than enter a number to indicate the desired temperature scale, enter 'C' or 'F'.

char scale;
char scale_new;
ret = scanf("%f %c", &temperature, &scale);
assert(ret == 2);

switch (scale) {
case 'C':
case 'c':
temperature_new = temperature*9/5 + 32;  // math is all FP
scale_new = 'F';
break;
case 'F':
case 'f':
temperature_new = (temperature - 32)*5/9;  // math is all FP
scale_new = 'C';
break;
default: