Using switch statements to call functions - c

I'm trying to write a program in C that uses switch statements to decide which called function to use to convert various values. My instructions were as follows:
"Create a program to convert Fahrenheit to Celsius, Celsius to Fahrenheit, inches to centimeter, and centimeters to inches. Put your choices into a switch statement so they will appear on the screen like below:
Select from the menu below to covert temperature or linear menus:
1 Convert Fahrenheit to Celsius
2 Convert Celsius to Fahrenheit
3 Convert Inches to Centimes
4 Convert Centimeters to Inches
5 Exit the program
Enter your selection:
ake each of the conversion routines a function that you will call from the main program. Each of the selections should be a case in a switch statement. Be sure to comment all your code according to the coding standards.
When I run the program and enter the choice followed by the value to convert, a weird number shows up followed by
ProgramExiting.ProgramExiting.
Here is my code:
#include <stdio.h>
void FahrenheitToCelsiusConversion (double conversionValue) {
double output;
output = conversionValue / (9.0 / 5.0) - 32;
printf("%d", output);
}
void CelsiusToFahrenheitConversion (double conversionValue) {
double output;
output = conversionValue * (9.0 / 5.0) + 32;
printf("%d", output);
}
void InchesToCentimetersConversion (double conversionValue) {
double output;
output = conversionValue * 2.54;
printf("%d", output);
}
void CentimetersToInchesConversion (double conversionValue) {
double output;
output = conversionValue / 2.54;
printf("%d", output);
}
int main(void) {
int conversionChoice;
double conversionValue;
printf("Select from the menu below to convert temperature or linear\n");
printf("menus:");
printf("\n");
printf("1 Convert Fahrenheit to Celsius\n");
printf("2 Convert Celsius to Fahrenheit\n");
printf("3 Convert Inches to Centimeters\n");
printf("4 Convert Centimeters to Inches\n");
printf("5 Exit the Program\n");
scanf("%d", &conversionChoice);
printf("Enter the value you wish to convert:\n");
scanf("%d", &conversionValue);
switch (conversionChoice) {
case 1:
FahrenheitToCelsiusConversion(conversionValue);
case 2:
CelsiusToFahrenheitConversion(conversionValue);
case 3:
InchesToCentimetersConversion(conversionValue);
case 4:
CentimetersToInchesConversion(conversionValue);
case 5:
printf("Program exiting.");
default:
printf("Program exiting.");
}
return 0;
}

You are missing breaks for a start. (so if you pick option 1 it will also perform options 2 3 4 and 5)
conversionValue is a double but you scan it in with %d. This means you aren't converting the value you think you are. Basic debug (printing your input values) would highlight that.
All your prints are trying to print a double with %d (should be %lf for doubles)
Combining output with calculations is bad. i.e. Your convert routines should return the converted value and the print should be outside the convert function.

As a follow on to your comments, understand that printf will print doubles using "%f" by default, however, to read a double with scanf you must use the l length-modifier, e.g. "%lf". A mismatch in format specifiers results in Undefined Behavior.
Further, as you found, your F->C conversion logic needs... help. The 32 is being subtracted at the wrong point, it should be:
void FahrenheitToCelsiusConversion (double conversionValue) {
double output;
output = (conversionValue - 32) / (9.0 / 5.0);
printf ("%.2f\n", output);
}
(note: the printf format change as well)
Further, in main() you need only a single call to printf (or fputs since no conversions are involved) to print the entire menu. When you terminate a line with a double-quote and the next begins with a double-quote, C will concatenate the strings, e.g.
printf ("\nSelect from the menu below to convert temperature or linear\n"
"menus:\n\n"
" 1 Convert Fahrenheit to Celsius\n"
" 2 Convert Celsius to Fahrenheit\n"
" 3 Convert Inches to Centimeters\n"
" 4 Convert Centimeters to Inches\n"
" 5 Exit the Program\n\n"
"choice: ");
Always, always validate all User Input, this means at minimum validating the return of scanf (and if not exiting after a matching failure -- you must read and discard all offending characters that remain in stdin because when a matching failure occurs, no further characters are removed from the input buffer and any offending characters that caused the matching failure remain unread just waiting to bite you again on your next attempt to read from the input buffer).
At minimum check that the number of conversions expected completed successfully (and you should further check that any numeric input is within range, if applicable), e.g.
if (scanf ("%d", &conversionChoice) != 1 || conversionChoice < 1 ||
conversionChoice > 5) {
fputs ("error: invalid input, or value out of range.\n", stderr);
return 1;
}
printf ("\nEnter the value you wish to convert: ");
if (scanf ("%lf", &conversionValue) != 1) {
fputs ("error: invalid value input.\n", stderr);
return 1;
}
You indicate you have added break statements to your switch statement, but after our discussion of the default fall-through behavior, do you understand why the following works?
switch (conversionChoice) {
case 1:
FahrenheitToCelsiusConversion(conversionValue);
break;
case 2:
CelsiusToFahrenheitConversion(conversionValue);
break;
case 3:
InchesToCentimetersConversion(conversionValue);
break;
case 4:
CentimetersToInchesConversion(conversionValue);
break;
case 5: /* here you CAN use fall-through */
default:
printf("Program exiting.");
break;
}
Putting all the pieces together, you can do something like the following:
#include <stdio.h>
void FahrenheitToCelsiusConversion (double conversionValue) {
double output;
output = (conversionValue - 32) / (9.0 / 5.0);
printf ("%.2f\n", output);
}
void CelsiusToFahrenheitConversion (double conversionValue) {
double output;
output = conversionValue * (9.0 / 5.0) + 32;
printf ("%.2f\n", output);
}
void InchesToCentimetersConversion (double conversionValue) {
double output;
output = conversionValue * 2.54;
printf ("%.2f\n", output);
}
void CentimetersToInchesConversion (double conversionValue) {
double output;
output = conversionValue / 2.54;
printf ("%.2f\n", output);
}
int main (void) {
int conversionChoice;
double conversionValue;
printf ("\nSelect from the menu below to convert temperature or linear\n"
"menus:\n\n"
" 1 Convert Fahrenheit to Celsius\n"
" 2 Convert Celsius to Fahrenheit\n"
" 3 Convert Inches to Centimeters\n"
" 4 Convert Centimeters to Inches\n"
" 5 Exit the Program\n\n"
"choice: ");
if (scanf ("%d", &conversionChoice) != 1 || conversionChoice < 1 ||
conversionChoice > 5) {
fputs ("error: invalid input, or value out of range.\n", stderr);
return 1;
}
printf ("\nEnter the value you wish to convert: ");
if (scanf ("%lf", &conversionValue) != 1) {
fputs ("error: invalid value input.\n", stderr);
return 1;
}
switch (conversionChoice) {
case 1:
FahrenheitToCelsiusConversion(conversionValue);
break;
case 2:
CelsiusToFahrenheitConversion(conversionValue);
break;
case 3:
InchesToCentimetersConversion(conversionValue);
break;
case 4:
CentimetersToInchesConversion(conversionValue);
break;
case 5: /* here you CAN use fall-through */
default:
printf("Program exiting.");
break;
}
return 0;
}
Example Use/Output
$ ./bin/tempconv
Select from the menu below to convert temperature or linear
menus:
1 Convert Fahrenheit to Celsius
2 Convert Celsius to Fahrenheit
3 Convert Inches to Centimeters
4 Convert Centimeters to Inches
5 Exit the Program
choice: 1
Enter the value you wish to convert: 212
100.00
Always compile with warnings enabled, and do not accept code until it compiles cleanly without warning. To enable warnings add -Wall -Wextra to your gcc or clang compile string. (add -pedantic for several additional warnings). For clang, instead you can use -Weverything. For VS (cl.exe on windoze), add /W3 (or use /Wall but you will get quite a few extraneous non-code related warnings). Read and understand each warning. They will identify any problems, and the exact line on which they occur. You can learn a lot by listening to what your compiler is telling you.
While not an error, C generally avoids the use of camelCase or MixedCase variable names in favor of all lower-case while reserving upper-case names for use with macros and constants. It is a matter of style -- so it is completely up to you, but failing to follow it can lead to the wrong first impression in some circles. See e.g. NASA - C Style Guide, 1994 As with anything outside the C-Standard, you are bound to find contra-indications, but generally camelCase or MixedCase are left to java or C++.
If you have any further questions, please just let me know.

Related

How to solve input duplicate problem In C [duplicate]

This question already has answers here:
What is the effect of trailing white space in a scanf() format string?
(4 answers)
problems with scanf("%d\n",&i) [duplicate]
(3 answers)
Closed 3 years ago.
when i input base value, it will not be recognized first in c
#include <stdio.h>
main(void)
{
float base, height, area;
printf("area of triangle=?\n");
printf("base=");
scanf("%f\n", &base);
printf("height=");
scanf("%f\n", &height);
area = base*height / 2;
printf("area = %f\n", area);
return 0;
}
You have 2 primary problems in your code.
(1) Do not include '\n' in your format specifier. Format specifiers such as "%f" skip whitespace by default. So use (subject to #2):
scanf("%f", &base)
(2) Validate EVERY user input by checking the return of the input function used. What happens if the user reached for the '4' key by hit 'R' my mistake? What happens then? (if it is the 1st digit -- undefined behavior as you blindly assume the input succeeded). Instead, validate the return, e.g.
if (scanf("%f", &base) != 1) {
fputs ("error: invalid float - base.\n", stderr);
return 1;
}
Putting it altogether, you could do:
#include <stdio.h>
int main (void)
{
float base, height, area;
fputs ("area of triangle=?\nbase=", stdout);
if (scanf("%f", &base) != 1) {
fputs ("error: invalid float - base.\n", stderr);
return 1;
}
fputs ("height=", stdout);
if (scanf("%f", &height) != 1) {
fputs ("error: invalid float - height.\n", stderr);
return 1;
}
area = base * height / 2.;
printf ("\narea = %f\n", area);
return 0;
}
(note: nit - there is no need to use the variadic printf function if there are no conversions involved, simply use fputs (or just puts if you want a default '\n' at the end). A good compiler will optimize this for your, but showing an understanding of what the proper tool for the job is has merit)
Example Use/Output
$ ./bin/trianglearea
area of triangle=?
base=3
height=4
area = 6.000000
Look things over and let me know if you have further questions.
Scanf using only format
scanf("%f",&base);
printf("base=");
scanf("%f", &base);
printf("\n");
printf("height=");
scanf("%f", &height);
printf("\n");

Trying to get a variable equal to other variables in C

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(NULL));
int score=0;
int loop=0;
int randNUM1=0;
char randSYMB1=0;
int randNUM2=0;
int correct_answer=0;
int answer=0;
for(loop=1;loop<=10;loop++)
{
randNUM1 = rand()%10; printf("%c", "0123456789"[randNUM1]);
randSYMB1 = rand()%4; printf("%c", "/*+-"[randSYMB1]);
randNUM2 = rand()%10; printf("%c\n", "0123456789"[randNUM2]);
printf("What is your answer?");
scanf("%d", &answer);
correct_answer=randNUM1/randNUM2 || randNUM1*randNUM2 ||
randNUM1+randNUM2 || randNUM1-randNUM2;
if (randSYMB1=="/")
{
printf("The correct answer is %d\n", randNUM1/randNUM2);
scanf("%d", &correct_answer);
score++;
}
else if (randSYMB1=="*")
{
printf("The correct answer is %d\n", randNUM1*randNUM2);
scanf("%d", &correct_answer);
score++;
}
else if (randSYMB1=="+")
{
printf("The correct answer is %d\n", randNUM1+randNUM2);
scanf("%d", &correct_answer);
score++;
}
else if (randSYMB1=="-")
{
printf("The correct answer is %d\n", randNUM1-randNUM2);
scanf("%d", &correct_answer);
score++;
}
printf("Your score is %d\n", score);
}
}
The code is for a simple calculation game, in which the user is asked 10 questions, which consist of randomly generating a number, then a symbol then another number, the answer is then stored, and then the user is told whether their answer was correct, and at the end of the 10 questions the user is given a score out of 10. My code seems to generate the numbers and the symbols randomly, and loops for 10 questions, but however, the code does not seem to take the IF statements into account, which then means that the correct answer isn't displayed, and thereofre, the score output to the user after every question is 0. Therefore, from what I can teel there is a problem with the IF statements, but I can't understand, what that problem is. I have also tried to use CASE statements instead, but the problem is still the same; the statements are not taken into account by the program. I cannot understand why the program does this. Is it a problem in the FOR loop, or is the probelm with the problem with the "correct_answer" variable? Please help!
Benny, much of the difficulty you are having just stems from apparently just starting in coding. There is nothing wrong with that, if you knew it all already, then you wouldn't need to learn... (and you are never really done learning how to program, hardware changes, standards change, etc.. It's a journey not a race)
First, if you have the option, declare all variables before you begin executing statements. This will keep your code portable to compilers still using the C89 standard (all windoze versions through Win7), e.g.
int score=0,
loop=0,
randNUM1=0,
randNUM2=0,
correct_answer=0,
answer=0;
char *symbol = "/*+-", /* use a string literal */
randSYMB1=0;
srand (time(NULL)); /* now begin executing statements */
It's a matter of style, but if you open the spacing up a bit, it will make your code more readable (especially for older eyes...). While you can save lines by cramming two expressions on each line or using the comma operator -- don't. It just makes your code harder to read (for you and anyone else). Sure, if it is stupid-short, then you can get away with it, e.g.
if (!a) b = 1;
otherwise, put each statement on it's own line:
for (loop = 1; loop <= 10; loop++)
{
/* separate all statements on it own line for readability. */
randNUM1 = rand() % 10; /* you have an int, use it */
printf ("%d", randNUM1);
randSYMB1 = symbol[rand() % 4]; /* get char from symbol string */
printf (" %c ", randSYMB1);
randNUM2 = rand()%10;
printf ("%d\n", randNUM2);
printf("What is your answer?: ");
if (scanf("%d", &answer) != 1) { /* validate ALL user input */
fscanf (stderr, "error: invalid input - answer.\n");
return 1;
}
Next, the crux of your issues are how to handle the logic of checking the math operation and the user's answer. All of the logic is based on what random character was generated with randSYMB1 = symbol[rand() % 4]; (my changes).
How do you take different actions based on a what one of a set of characters could be? Well, you can daisy-chain a whole string of if and else if statements together, or, just use a switch statement:
switch (randSYMB1) {
case '/': correct_answer = randNUM1 / randNUM2;
break;
case '*': correct_answer = randNUM1 * randNUM2;
break;
case '+': correct_answer = randNUM1 + randNUM2;
break;
case '-': correct_answer = randNUM1 - randNUM2;
break;
}
That leaves your a single simple comparison to determine if the correct answer was entered:
if (answer == correct_answer) {
printf ("Correct!\n");
score++;
}
else
printf ("Incorrect. Correct answer: %d\n", correct_answer);
printf ("Your current score is: %d\n\n", score);
(note: for division, the user must enter the result of what integer division would produce)
Putting it altogether, you could boil your code down to:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main (void) {
int score=0,
loop=0,
randNUM1=0,
randNUM2=0,
correct_answer=0,
answer=0;
char *symbol = "/*+-", /* use a string literal */
randSYMB1=0;
srand (time(NULL));
for (loop = 1; loop <= 10; loop++)
{
/* separate all statements on it own line for readability. */
randNUM1 = rand() % 10; /* you have an int, use it */
printf ("%d", randNUM1);
randSYMB1 = symbol[rand() % 4]; /* get char from symbol string */
printf (" %c ", randSYMB1);
randNUM2 = rand()%10;
printf ("%d\n", randNUM2);
printf("What is your answer?: ");
if (scanf("%d", &answer) != 1) { /* validate ALL user input */
fscanf (stderr, "error: invalid input - answer.\n");
return 1;
}
switch (randSYMB1) {
case '/': correct_answer = randNUM1 / randNUM2;
break;
case '*': correct_answer = randNUM1 * randNUM2;
break;
case '+': correct_answer = randNUM1 + randNUM2;
break;
case '-': correct_answer = randNUM1 - randNUM2;
break;
}
if (answer == correct_answer) {
printf ("Correct!\n");
score++;
}
else
printf ("Incorrect. Correct answer: %d\n", correct_answer);
printf ("Your current score is: %d\n\n", score);
}
return 0;
}
Example Use/Output
C:\Users\david\Documents\dev\src-c\tmp>bin\mathtest.exe
9 + 3
What is your answer?: 12
Correct!
Your current score is: 1
8 * 8
What is your answer?: 64
Correct!
Your current score is: 2
5 + 7
What is your answer?: 12
Correct!
Your current score is: 3
6 - 4
What is your answer?: 2
Correct!
Your current score is: 4
6 / 4
What is your answer?: 1
Correct!
Your current score is: 5
7 * 9
What is your answer?: 63
Correct!
Your current score is: 6
5 / 6
What is your answer?: 0
Correct!
Your current score is: 7
8 * 2
What is your answer?: 16
Correct!
Your current score is: 8
0 / 1
What is your answer?: 0
Correct!
Your current score is: 9
9 + 7
What is your answer?: 16
Correct!
Your current score is: 10
Look things over and let me know if you have further questions.
There are several problems with your code. randSYMB1 will have a value of 0 to 3, none of which corresponds to the ascii values of /*+-.
Change the if statements to:
if (randSYMB1==0)
and accordingly to the rest. Also, you should never write something like:
char c;
...
if(c == "x")
You should use single quotes:
if(c == 'x')
This line:
correct_answer=randNUM1/randNUM2 || randNUM1*randNUM2 ||
randNUM1+randNUM2 || randNUM1-randNUM2;
is complete jibberish. Move the calculation of correct value inside the if statements.
This:
printf("%c", "0123456789"[randNUM1]);
works, but it's pretty insane. This is better:
printf("%d", randNUM1);
I guess it's ok as a quick workaround for randSYMB1 but there's no reason at all with the operands.
Here is a working version of the for loop:
for(loop=1;loop<=10;loop++)
{
randNUM1 = rand()%10;
printf("%d", randNUM1);
randSYMB1 = rand()%4;
printf("%c", "/*+-"[randSYMB1]);
randNUM2 = rand()%10;
printf("%d\n", randNUM2);
printf("What is your answer?");
scanf("%d", &answer);
if (randSYMB1==0)
correct_answer=randNUM1/randNUM2;
else if (randSYMB1==1)
correct_answer=randNUM1*randNUM2;
else if (randSYMB1==2)
correct_answer=randNUM1+randNUM2;
else if (randSYMB1==3)
correct_answer=randNUM1-randNUM2;
printf("The correct answer is %d\n", correct_answer);
if(answer == correct_answer)
score++;
printf("Your score is %d\n", score);
}
If never executes because randSYMB1 is number between 0-3, and not "/*-+". Also i suggest seeding random first, but in this case it doesn't matter.

in C, trying to use a program that converts Fahrenheit to kelvin [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
But the calculation doesn't work or change when I run it and plug in any random number...need some guidance. I'm a novice to C and programming in general so please include easy to understand help.
#include <stdio.h>
double const change_celcius = 32.0;
double const change_kelvin = 273.15;
void temperatures(double n);
int main(void)
{
int q = 'q';
double user_number;
printf("Enter the fahrenheit: \n");
scanf("%f", &user_number);
while (user_number != q)
{
temperatures(user_number);
printf("\n");
printf("Enter the fahrenheit: \n");
scanf("%f", &user_number);
}
}
void temperatures(double n)
{
double celsius, kelvin;
celsius = 5.0 / 9.0 * (n - change_celcius);
kelvin = 5.0 / 9.0 * (n - change_celcius) + change_kelvin;
printf("fahrenheit: %.2f - celsius is: %.2f - kelvin is: %.2f",
n, celsius, kelvin);
}
I don't believe the all the use %lf instead of %f comments, by themselves, fix your program. The handling of q (for "quit") is also problematic so let's fix that too. First, we'll use POSIX function getline() to read it into a string and test if it's "q". If not, we'll sscanf it into a double and use it as our temperature:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
double const change_celsius = 32.0;
double const change_kelvin = 273.15;
void temperatures(double n)
{
double celsius = 5.0 / 9.0 * (n - change_celsius);
double kelvin = 5.0 / 9.0 * (n - change_celsius) + change_kelvin;
printf("fahrenheit: %.2f - celsius is: %.2f - kelvin is: %.2f\n", n, celsius, kelvin);
}
int main(void)
{
char *user_string = NULL;
ssize_t user_string_length;
size_t user_string_capacity = 0;
while (1)
{
printf("Enter the fahrenheit: ");
if ((user_string_length = getline(&user_string, &user_string_capacity, stdin)) < 1)
break;
if (strncmp(user_string, "q\n", (size_t) user_string_length) == 0)
break;
double user_number;
if (sscanf(user_string, "%lf", &user_number) == 1)
temperatures(user_number);
}
if (user_string != NULL)
free(user_string); // free memory allocated by getline()
if (user_string_length == -1)
putchar('\n'); // output courtesy newline if user used ^D to exit
return(0);
}
We check the return value of sscanf so that bad input won't cause the program to recalculate using the last good input. Instead, it will just prompt again for input.
You need to use "%lf" in scanf() and print() to read and write the value of type double.
Note that the printf() will work with "%f" too.
For more details please refer : Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?
There are several issues that can be addressed in your code. First, always (Always, in case it wasn't clear) check the return of scanf. That is the only way you know whether the expected number of conversions took place -- and whether you have an actual value to work with in your code.
The return also holds the key to exiting the loop when the user enters 'q' (or anything that causes the conversion to double to fail). By simply checking
if (scanf(" %lf", &user_number) == 1)
You can determine whether to process the value as a temperature, or tell the user has indicated exit.
Another tip, never (Never) write:
printf ("\n");
Why would you want to call a variadic function simply to output a single char? That is what putchar (or fputc) is for, e.g.:
putchar ('\n');
Putting those pieces together, and noting that %lf is used as the format specifier for double, you can rewrite your code, and format the output in quite a bit fewer lines, e.g.
#include <stdio.h>
double const change_celcius = 32.0;
double const change_kelvin = 273.15;
void temperatures (double n);
int main(void)
{
double user_number;
while (printf ("\nEnter temp in degrees fahrenheit: ") &&
scanf(" %lf", &user_number) == 1)
temperatures(user_number);
return 0; /* main() is type 'int' and returns a value to the shell */
}
void temperatures (double n)
{
double celsius, kelvin;
celsius = 5.0 / 9.0 * (n - change_celcius);
kelvin = 5.0 / 9.0 * (n - change_celcius) + change_kelvin;
printf(" fahrenheit: % 7.2lf\n celsius is: % 7.2lf\n kelvin is : % 7.2lf\n",
n, celsius, kelvin);
}
Example Use/Output
$ ./bin/temps
Enter temp in degrees fahrenheit: 212
fahrenheit: 212.00
celsius is: 100.00
kelvin is : 373.15
Enter temp in degrees fahrenheit: 0
fahrenheit: 0.00
celsius is: -17.78
kelvin is : 255.37
Enter temp in degrees fahrenheit: 68
fahrenheit: 68.00
celsius is: 20.00
kelvin is : 293.15
Enter temp in degrees fahrenheit: q
Always compile your code with at minimum -Wall -Wextra warnings enabled (and if you really want to drill down, add -pedantic). Read the warnings and fix them. All of your code should compile without warning before you consider your code reliable at this stage of the game.
Look all answers over, and let me know if you have any questions.
To read Double use %lf instead of %f.
for double printf() will work with %f also.
The calculation seems to be okay; however the you are not reading in the words properly
scanf("%f", &user_number);
You are stating you are reading in a float, yet you are declaring user_name as a double. If you wanted to use a float, you would need to change the user_name declaration from double to float. If you wanted to use a double use "%f".

Keeping getting 0.00 as an answer

I keep receiving 0 as my answer at the end. Please help
#include <stdio.h>
int Fahrenheit = 0;
double Celsius = 0.0;
double main(void)
{
printf("This program will convert the temperature from fahrenheit to celsius.\n");
printf("Please type in the temperature in fahrenheit followed by the enter key.\n");
scanf("%d%",&Fahrenheit);
Celsius = (5/9) * (Fahrenheit-32) ;
printf("Your temperature in celsius is %3.2f.\n", Celsius);
return(0);
}
Because of integer division, change 5 / 9 to 5.0 / 9.0. Also, make Fahrenheit double and change scanf() to
if (scanf("%lf", &Fahrenheit) == 1)
{
Celcius = 5.0 * (Fahrenheit - 32.0) / 9.0;
printf("Your temperature in celsius is %3.2f.\n", Celsius);
}
Also:
There is absolutely no reason to make your variables global.
I have seen many peculiar main() signatures and now
double main(void);
Ignoring the return value of scanf() would lead to potential undefined behavior. If I had a teacher that forbids if statements but requires scanf() I would quit with him and find a good instructor.
But of course if I was learning how would I know that ignoring ٰscanf()'s return value is bad? And that's the sad part, many even don't know that it returns a value or that it fails, for instance try this
int value;
if (scanf("%d", &value) != 1)
fprintf(stderr, "Error, invalid input\n");
else
fprintf(stdout, "Ok, so your input is `%d'\n", value);
type "abcd" instead of a number, what happens?

Calculator program requires + and - to be entered twice

I am writing a simple calculator program to add, subtract, multiply, divide and do exponential equations. The program must repeat until "q0" is entered and it must have two functions called by the main function like I have written. The problem is when I run the program the first number shows up fine and then I can multiply, divide, and do exponential functions fine but if I want to add or subtract I must enter the + or - twice for it to count it. This is the program I have written:
#include <stdio.h>
#include <math.h>
void scan_data(char *oprter, double *oprand);
void do_next_op(char oprter, double oprand, double *accum);
int
main(void)
{
double nmber, /* input/output - operand */
total; /* output - final result */
char sign; /* input/output - operator */
total = 0;
do {
scan_data(&sign, &nmber);
do_next_op(sign, nmber, &total);
} while (sign != 'q');
printf("Final result is %.2f", total);
return (0);
}
/*
* Gathers operator and operand to perform calculation
* Post: results are stored in cells pointed to by oprter, and oprand
*/
void
scan_data(char *oprter, /* input - amount being withdrawn */
double *oprand) /* output - number of tens */
{
double amount;
amount = 0;
scanf("%c", &*oprter);
scanf("%lf", &amount);
*oprand = amount;
}
/*
* Performs calculation and displays results
* Pre: oprter and oprand are defined
* Post: function results are stored in cell pointed to by accum
*/
void
do_next_op(char oprter,
double oprand,
double *accum)
{
double tot_amount;
tot_amount = *accum;
switch(oprter)
{
case '+':
tot_amount = (tot_amount + oprand);
printf("result so far is %.2f\n", tot_amount);
break;
case '-':
tot_amount = (tot_amount - oprand);
printf("result so far is %.2f\n", tot_amount);
break;
case '*':
tot_amount = tot_amount * oprand;
printf("result so far is %.2f\n", tot_amount);
break;
case '/':
tot_amount = tot_amount / oprand;
printf("result so far is %.2f\n", tot_amount);
break;
case '^':
tot_amount = pow(tot_amount, oprand);
printf("result so far is %.2f\n", tot_amount);
break;
}
*accum = tot_amount;
}
An example of what it is doing follows:
+5
result so far is 5.00
+5
-5
++5
result so far is 10.00
--5
result so far is 5.00
*2
result so far is 10.00
/2
result so far is 5.00
^2
result so far is 25.00
q0
Final result is 25.00
The problem is most likely that scanf leaves the newline in the input buffer when you do
scanf("%lf", &amount);
That means that the next call to
scanf("%c", oprter);
it will read that newline.
This can be solved by asking scanf to read and skip all leading whitespace by adding a single space to the scanf format string like
scanf(" %c", oprter);
// ^
// |
// Note space here

Resources