Keeping getting 0.00 as an answer - c

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?

Related

Using switch statements to call functions

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.

How to force program to recognize word and stop

I have a problem related to different types of variables at the input type.
My program is simple. I type the temperature in Celsius, program prints Celsius and Fahrenheit temperature value and then loops itself asking for next value in Celsius. If you type "-99999" it will stop.
I wanted to change it to stop when I type a word "elo" (It basically means "Bye" in Polish slang :) ) but after a few hours of trying I gave up...
I'll appreciate any help!
#include <stdio.h>
float fahrenheit(long);
int main()
{
int celsius;
printf("Type the temperature in celsius: ", &celsius);
scanf_s("%ld", &celsius);
while (celsius != -99999) {
printf("%ld %6.1f\n", celsius, fahrenheit(celsius));
printf("Type the temperature in celsius: ", &celsius);
scanf_s("%ld", &celsius);
}
}
float fahrenheit(long celsius)
{
return (float) 1.8*celsius + 32.0;
}
There are a number of ways to do this. I think the easiest is to detect scanf failed to read a number and then fall back on string input.
int celcius;
char buff[10];
bool elo = false;
int args_read = scanf(" %d", &celcius);
if (args_read < 1) {
// User must have put in a non-number
scanf(" %s", buff);
if (strcmp(buff, "elo") == 0) {
elo = true;
}
}
The line printf("Type the temperature in celsius: ", &celsius); is strange. Didn't your compiler complain about this? Why are you providing the address of celsius as an argument to this call? Another mistake is scanf_s("%ld", &celsius);, which reads in celsius as a long int value, when you have only declared celsius as an int. It's a good idea to always enable compiler warnings when you're working on code.
As mentioned by #StephenDocy, you need to read in the input as a string first, then check to see if it is a number or your stop word.
You can also simplify your code a bit to avoid repeating lines like printf("Type the temperature in celsius: ", &celsius); more than necessary. I think it would also make sense to treat celsius as a floating point value
#include <stdio.h>
#include <string.h>
float fahrenheit(float);
int main() {
float celsius;
char input_buffer[256];
while (1) {
printf("Type the temperature in celsius:\n");
scanf("%255s", input_buffer);
if (strcmp("elo", input_buffer) == 0) break;
if (sscanf(input_buffer, "%f", &celsius) == 1) {
printf("%6.1f %6.1f\n", celsius, fahrenheit(celsius));
}
}
return 0;
}
float fahrenheit(float celsius) {
return 1.8 * celsius + 32.0;
}

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".

Not calling address, but float is returning 0.000-

I have this code here: (Using CLion on a Mac)
#include <stdio.h>
float convFtoC(int *, float *);
int main()
{
int min, increment, fahrenheit;
float celsius;
increment = 5;
min = 0;
printf("Please enter a max temperature in Fahrenheit: \n");
scanf("%d", &fahrenheit);
convertFtoC(&fahrenheit, &celsius);
printf("%d degrees Fahrenheit converted is %.4f degrees Celsius \n", fahrenheit, celsius);
printf("%d is the lowest F. The temperatures increment by %d.", min, increment);
return 0;
}
float convFtoC(int *pfahrenheit, float *pcelsius)
{
*pcelsius = (*pfahrenheit - 32) * (5 / 9);
return 0;
}
My output for celsius becomes 0.00 for all inputs and I can't figure out why. I'm not calling the address of celsius so I'm confused as to why this is happening. Here is example output:
Please enter a max temperature in Fahrenheit:
60
60 degrees Fahrenheit converted is 0.00 degrees Celsius
0 is the lowest F. The temperatures increment by 5.
Process finished with exit code 0
You've to force arithmetic to be run in floating point mode.
This can be done by changing 5 to 5.0 or 9 to 9.0:
*pcelsius = (*pfahrenheit - 32) * (5.0 / 9);
Although there's no need for convFtoC to return type being float; It can be void.
Also, You have a typo mistake in calling convFtoC

C SIMPLE Temperature converter / Celsius to Fahrenheit UNKNOWN errors & output

I just started programming in C a few days ago and have a few questions:
The following program converts Celsius into Fahrenheit and vice versa. I am getting a Segmentation fault error.
#include<stdio.h>
#include <string.h>
#include<stdlib.h>
float c2f(float);
float f2c(float);
float Fahrenheit,Celsius;
int main(int argc, char *argv[])
{
/**
* Check for the expected number of arguments (3)
* (0) program name
* (1) flag
* (2) temperature
*/
if (argc!=3)
printf("Incorrect number of arguments");
if (!strcmp(argv[1], "->f"))
{
// convert the string into a floating number
char *check;
float Celsius = strtod(argv[2], &check);
// process from celsius to fahrenheit
Fahrenheit = c2f(Celsius);
printf("%5.2f°C = %5.2f°F",Celsius, Fahrenheit);
}
else if (!strcmp(argv[1], "->c"))
{
// convert the string into a floating number
char *check;
float Fahrenheit = strtod(argv[2], &check);
// process from fahrenheit to celsius
Celsius = f2c(Fahrenheit);
printf("%5.2f°F = %5.2f°C", Fahrenheit, Celsius);
}
else
printf("Invalid flag\n");
} // main
float c2f(float c)
{
return 32 + (c * (180.0 / 100.0));
}
float f2c(float f)
{
return (100.0 / 180.0) * (f - 32);
}
Also, I want my output to be like this:
**> TemperatureConverter ->f 10.0
10.00°C = 50.00°F**
This should convert 10C into F.
For F to C, the output should be:
TemperatureConverter ->c 50.0
50.00°F = 10C**
the error is
if (!strcmp(argv[1], "->f")
it's missing a final parenthesis, should be
if (!strcmp(argv[1], "->f"))
and you made the same mistake twice. 1 paren for strcmp(), 1 for if()
you should include string.h. Also, you should put you functions f2c and c2f before main.
also you wrote
prinf
try with a t before the f
printf
finally you need
exit(0);
after the first if. eg
if (argc!=3)
{
printf("Incorrect number of arguments");
exit(0);
}
otherwise the rest of the program runs and you get seg fault. Welcome to programming.
Slight nitpicking:
float c2f(float);
float f2c(float);
While it's technically correct, remember to include the variable name as well in your function declarations. It makes it easier to read.
As an example
float c2f(float c);
I used this code :
/* Declare Initial library for functions */
#include<stdio.h>
#include<conio.h>
/* Main function*/
void main()
{
/* data type(float),variable(c,f)*/
float c, f;
/* printf function from stdio.h library , for printing level*/
printf("Enter temp. in Celsius: ");
/* scanf for inserting data in variable*/
scanf("%f",&c);
/* Fahrenheit rules*/
f = c * 9/5 + 32;
/* Result will display in this line */
printf("Temp. in Fahrenheit: %f",f);
/* getch function from conio.h library, used to write a character to screen*/
getch();
}

Resources