I have just begun to learn the C language and wanted to start off small with a temperature conversion calculator. The program works, and I'm looking for feedback on do's and don'ts as I am sure there are at least a few errors in technique that can be improved. (I just realized Fahrenheit is spelled incorrectly).
/*Calculates user provided temperature in Farenheight or Celsius depending on option chosen.*/
#include "stdafx.h" //don't actually know what this is for however will not compile without it.
#include <stdio.h>
#include <stdBool.h>
#include <conio.h>
/*Calculator options*/
#define option_1 1
#define option_2 2
#define option_3 3
#define option_4 4
void welcome();
void calculator();
void get_input(_Bool*, int*, float*);
void display_result(int, float);
float F_to_C(float);
float C_to_F(float);
int main(void)
{
welcome();
calculator();
_getch();
}
void welcome() /*Welcome message + instruction*/
{
printf("Welcome to the Temperaure Conversion Calculator\n\n");
printf("Please select an option:\n\n");
printf("Options:\t1)F to C\t2)C to F\t3)OFF\n\n");
}
void calculator() /*Conversion Calclator*/
{
int option = 0;
float input_temp = 0.0f;
_Bool calc_off = 0;
while (!calc_off)
{
get_input(&calc_off, &option, &input_temp);
if (option == option_1) /*F to C*/
{
display_result(option_1, input_temp);
}
else if (option == option_2) /*C to F*/
{
display_result(option_2, input_temp);
}
}
}
void get_input(_Bool *calc_off, int *option, float *input_temp) /*Retrieve user input*/
{
int trash = 0;
int data_check;
printf("Select option: "); scanf_s("%d", option); /*Obtains option*/
scanf_s("%c", &trash); /*obtains newline character that will cause infinite loop*/
while (*option != 1 && *option != 2 && *option != 3) /*incorrect option selection*/
{
display_result(option_4, option_4);
scanf_s("%d", option);
scanf_s("%c", &trash); /*Collects garbage newline character (Prevents infinite loop)*/
}
if (*option == option_3) /*Calculator off*/
{
*calc_off = 1;
display_result(option_3, option_3);
return;
}
printf("Temperature: "); scanf_s("%f", input_temp); /*Obtains temperature*/
return;
}
void display_result(int option, float input_temp) /*Display results*/
{
if (option == option_1)
printf("Farenheight to Celsius of %.1f F is: %.1f C\n", input_temp, F_to_C(input_temp));
else if (option == option_2)
printf("Celsius to Farenheight of %.1f F is: %.1f F\n", input_temp, C_to_F(input_temp));
else if (option == option_3)
printf("Calculator OFF\n");
else if (option == option_4)
printf("Invalid option choice, please try again...\nOption: ");
}
float F_to_C(float input_temp) /*Convert Farenheight to Celsius*/
{
return (5.0 / 9.0)*(input_temp - 32);
}
float C_to_F(float input_temp) /*Convert Celsius to Farenheight*/
{
return (9.0 / 5.0)*(input_temp)+32;
}
stdout
, thus the prompt will not be displayed before waiting for user input on any system that line buffersstdout
. (windows environments tend not to, and leavestdout
unbuffered when interactive) \$\endgroup\$