issue storing information into variable in C [duplicate] - c

This question already has answers here:
Problems with scanf and doubles [duplicate]
(2 answers)
Closed 8 years ago.
I wrote the following code for an intro to C class. However for some reason I cannot figure out why the scanf will not store the input into the fahrenheit variable therefore not allowing me to do the calculation correctly. I switched the starting value from 0 to 212 to make sure that my calculation is correct however it still doesn't allow me to update.
#include <stdio.h>
int main(void){
double fahrenheit = 212.00;
double celcius = 0;
//prompt the user for the information
printf("Enter a temperature in degrees Fahrenheit >");
//store the information in the Fahrenheit var.
scanf("%f", &fahrenheit);
//calculate the change in metrics
celcius = (fahrenheit-32)*.5556 ;
printf("%f degrees Fahrenheit is equal to %f degrees celcius\n",fahrenheit,celcius);
}

The proper printf and scanf format to use with double argument is %lf. Not %f, but %lf. Don't use %f with double. It should be
scanf("%lf", &fahrenheit);
...
printf("%lf degrees Fahrenheit is equal to %lf degrees celcius\n",
fahrenheit, celcius);
Note that %f will work with double in printf (not in scanf), but using it in that fashion is still a bad habit, which only fuels the popular beginner's misconception that printf and scanf are somehow "inconsistent" in that regard.
The matching between format specifiers and argument types is well-defined and consistent between printf and scanf:
%f is for float
%lf is for double
%Lf is for long double.

You're reading a float (with %f) and yet you're storing it inside a double.
Either
Change the type of fahrenheit to float
Change your scanf call to `scanf("%lf", &fahrenheit);

You declared your variable as double fahrenheit; but used the scanf() specifier for float, try this
#include <stdio.h>
int main(void) {
float fahrenheit = 212.00;
/* ^ float, instead of double */
float celcius = 0;
// prompt the user for the information
printf("Enter a temperature in degrees Fahrenheit > ");
// store the information in the Fahrenheit var.
if (scanf("%f", &fahrenheit) != 1) // check that scanf succeeded
return -1;
// calculate the change in metrics
celcius = (fahrenheit-32)*.5556 ;
printf("%f degrees Fahrenheit is equal to %f degrees celcius\n",fahrenheit,celcius);
return 0;
}
or change the scanf() specifier to "%lf" the printf() specifier is ok for both.
Also, you better make sure scanf() succeeded reading.

Related

C program to determine temperature conversions not working

I'm trying to create a program that asks the user what conversion the user wants to do, then scans for the number they want to convert, then does the conversion and spits it out.
Here are the instructions that include desired outputs:
Building on assignment one, create a program to with the choice of convert Celsius to Fahrenheit or Fahrenheit to Celsius using “ifelse” statement to chose which conversion you want to use. Be sure to include the correct header in your .C file. Use the K and R formatting. Name your file “first Initial last name-assingment2.c” ex: “rgalus-assingment2.c” Below is what I expect the program output to look like:
Enter 1 to convert Celsius to Fahrenheit
Enter 2 to convert Fahrenheit to Celsius
Enter 0 to exit
1
10
10 degrees Celsius is equal to 50 degrees Fahrenheit
Enter 1 to convert Celsius to Fahrenheit
Enter 2 to convert Fahrenheit to Celsius
Enter 0 to exit
2
32
32 degrees Fahrenheit equals 0 degrees Celsius
Enter 1 to convert Celsius to Fahrenheit
Enter 2 to convert Fahrenheit to Celsius
Enter 0 to exit
0
“exit the program”
My issue is that while it will scan my choice, the program ends before I can enter a number to convert.
Below is my code:
#include <stdio.h>
int main(void) {
double userConversionChoice;
double CelsiusToFahrenheitResult;
double FahrenheitToCelsiusResult;
double userConversionNumber;
printf("Enter 1 to convert Celsius to Fahrenheit\n");
printf("Enter 2 to convert Fahrenheit to Celsius\n");
printf("Enter 0 to exit\n");
scanf("%d", userConversionChoice);
if (userConversionChoice == 1) {
scanf("%d", userConversionNumber);
CelsiusToFahrenheitResult = (1.8 * userConversionNumber) + 32.0;
printf("%d degrees Celsius equals %d degrees Fahrenheit", userConversionNumber, CelsiusToFahrenheitResult);
}
else {
if (userConversionChoice == 2) {
scanf("%d", userConversionNumber);
FahrenheitToCelsiusResult = (userConversionNumber - 32.0) / 1.8;
printf("%d degrees Fahrenheit equals %d degrees Celsius", userConversionNumber, FahrenheitToCelsiusResult);
}
else {
printf("exit the program");
}
}
return(0);
}
The immediate issues are:
scanf takes pointers to variables (&x), not variables. That's because a normal function call f(x) cannot modify x (arguments are passed by value).
The %d conversion specifier reads an integer (and expects a corresponding int * argument). Your variables are of type double, so either you need to change them to int or use %lf.
Similarly, printf %d expects an int, not a double. The format specifier for double is %f.
You should check the return value when you use scanf to make sure a value was read successfully. scanf returns the number of input items assigned.
Thus:
int userConversionChoice;
if (scanf("%d", &userConversionChoice) != 1) {
fprintf(stderr, "failed to read input\n");
return EXIT_FAILURE; // EXIT_FAILURE is in <stdlib.h>
}
double userConversionNumber;
if (scanf("%lf", &userConversionNumber) != 1) {
printf("%.2f degrees Celsius equals %.2f degrees Fahrenheit", userConversionNumber, CelsiusToFahrenheitResult);
In the long term, I recommend avoiding scanf for user input altogether. It is hard to use correctly, it makes for confusing user interfaces (e.g. if a user just hits enter, your program will sit there seemingly frozen, but actually still waiting for input in scanf), and it's hard to recover from errors.
For more intuitive behavior, read whole lines of input (using e.g. fgets) and convert them afterwards (using e.g. sscanf or strtod / strtol):
char buf[200];
...
printf("enter a number: ");
fflush(stdout);
if (!fgets(buf, sizeof buf, stdin)) {
return 0; // end-of-input was reached
}
double num = strtod(buf, NULL); // convert input to number
userConversionNumber is a double. You are reading into it using %d which is the conversion specifier for integers.
And you are not using the & (address of) operator when reading into it.
scanf("%d", userConversionChoice);
So define userConversionChoice as an int and read the input this way:
scanf("%d", &userConversionChoice);
Behaviour of scanf:
The scanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. Otherwise, the function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.
So it is good practice to check the return value of scanf before further processing.
Your use of scanf (and printf) is incorrect.
The format string must match the type of parameter you are using. You can get away with this on printf() sometimes, but not scanf().
For scanf(), you must also pass the address-of (i.e.: a pointer to) the variable you wish to store into.
#include <stdio.h>
int main(void)
{
int userConversionChoice;
double CelsiusToFahrenheitResult;
double FahrenheitToCelsiusResult;
double userConversionNumber;
printf("Enter 1 to convert Celsius to Fahrenheit\n");
printf("Enter 2 to convert Fahrenheit to Celsius\n");
printf("Enter 0 to exit\n");
printf("Choice> ");
scanf("%d", &userConversionChoice);
if (userConversionChoice == 1)
{
printf("Temperature> ");
scanf("%lf", &userConversionNumber);
CelsiusToFahrenheitResult = (1.8 * userConversionNumber) + 32.0;
printf("%0.2lf degrees Celsius equals %0.2lf degrees Fahrenheit", userConversionNumber, CelsiusToFahrenheitResult);
}
else if (userConversionChoice == 2)
{
printf("Temperature> ");
scanf("%lf", &userConversionNumber);
FahrenheitToCelsiusResult = (userConversionNumber - 32.0) / 1.8;
printf("%0.2lf degrees Fahrenheit equals %0.2lf degrees Celsius", userConversionNumber, FahrenheitToCelsiusResult);
}
else
{
printf("exit the program");
}
return(0);
}
Obviously there's some room here for optimisation, since there's two lots of code inputting the temperature.

Scanf not reading in double

I am trying to read in a double value continuously from the user using scanf.
Code:
printf("Enter A value: \n");
double input;
int result = scanf("%f", &input);
printf("INPUT: %f\n", input);
The output is
INPUT: 0.000
You lied to the compiler: when scanning, %f says you supply a pointer to float. But you provided a pointer to double.
To fix, either use %lf or declare input as float.
Note that there is an asymmetry with printf formats, which uses %f for both float and double arguments. This works because printf arguments are promoted to double (and are not pointers).
I am trying to read in a double value continuously from the user using scanf.
To do so you need a loop, like the following:
while(scanf("%lf", &input) == 1) {
//code goes here...
printf("INPUT: %lf\n", input);
//code goes here...
}
Note that, as the primitive type of input is double, you need to use %lf instead of %f (%fused for float).

C programming - Output result in decimals

At the momemt, i'm learning the C and the basics of the language, but I have a problem with my code. When I multiply two numbers, I cant get the decimals, even I float the numbers I enter.
My code:
int main()
{
double result_met, km;
result_met = km = 0.0f;
/*Display text*/
printf("Enter values of the distance between the two cities in km's\n");
scanf_s("%d", &km);
/*Formular for a simple km conversion*/
result_met = km * 1000.0f;
/*Result print*/
printf("Meter:%d", result_met);
printf("\nWaiting for a character to be pressed from the keyboard to exit.\n");
getch();
return 0;
}
The format specifiers are incorrect - it should be %lf - %d is for int.
scanf_s("%lf", &km);
/*Formular for a simple km conversion*/
result_met = km * 1000.0f;
/*Result print*/
printf("Meter:%lf", result_met);
Format string specifications
The format specifier for double is %lf, not %d
You may as well use a float instead of a double, it saves memory (which is important when you begin to write big programs), then you must use the format specifier %f (the "l" in %lf is for "long", because a double is a long float)
When treating decimals, you want to print only a few decimals on the screen (to avoid the printing of a "2.50000001"), then you can use the format specifier %.3f if you want 3 and only 3 digits printed (3 can be any integer).
for example, the following code :
printf("%.2f\n",3.1415);
has the following output :
3.14
the printf function has many different format specifier, that can be very useful.
Go see the cpluplus.com reference if you want to learn more about it

decimal of numbers in c

I just asked a question but couldn't get what I want, and couldn't edited and reply as it is too long. My question is the same and it is the link to that question.how to keep decimals in c
#include<stdio.h>
int main()
{
float b,c,;
int a,kk;
printf("Welcome to the unit conversion program\n");
printf("This program can convert the measurements of;\n");
printf("1-Length\n");
printf("2-Mass\n");
printf("Please select the number that corresponds to the measurement you want to convert in:\n");
scanf("%d",&a);
if (a==1){
printf("Your number will be converted from inches to centimeters.\n");
printf("Please enter the length.\n");
scanf("%f",&b);
c=b*2.54;
printf("%f inch is %f cm.",b,c);
scanf("%d",kk); \. to avoid to shut the cmd windows .\
}
else if (a==2){
printf("Your number will be converted from pounds (lbs) to kilograms");
printf("Please enter the mass.\n");
scanf("%d",&b);
c=b*0.45359237;
printf("%d lbs is %d kgs.",b,c);
}
return 0;
}
The error is that %d in the format specifier of both scanf and printf represents decimal, so it expects an int (in the case of scanf, a pointer to int)
Since you are declaring b and c as float, %d in the lines
scanf("%d",&b);
printf("%d lbs is %d kgs.",b,c);
should be changed to %f respectively.
A little piece of advice: use double in stead of float. It provides more precision, its performance is better in many machines. The downside is that it occupies more space than float, but that's not a problem in most cases.
You should use %f in printf and %lf in scanf in case you are using double.
Change:
scanf("%d",&b);
printf("%d lbs is %d kgs.",b,c);
to:
scanf("%f",&b);
printf("%f lbs is %f kgs.",b,c);
You declared b as float and taking input as a decimal & later printing both float b,c as decimal? Please study a book Deital & Deital for C/C++ is an amazing book.

Programming Data Types

I am trying to learn C and have come up with the following small program.
#include "stdafx.h"
void main()
{
double height = 0;
double weight = 0;
double bmi = 0;
printf("Please enter your height in metres\n");
scanf_s("%f", &height);
printf("\nPlease enter your weight in kilograms\n");
scanf_s("%f", &weight);
bmi = weight/(height * height);
printf("\nYour Body Mass Index stands at %f\n", bmi);
printf("\n\n");
printf("Thank you for using this small program. Press any key to exit");
getchar();
getchar();
}
The program compiles perfectly, however the answer returned by the program does not make sense. If I enter 1.8 for height and 80 for weight, the bmi is like 1.#NF00 which does not make sense.
What am I doing wrong?
When using scanf with a double, you must use the %lf specifier, as pointers are not promoted with scanf.
For more info, read the following question:
Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?
scanf (and scanf_s) format %f expects pointer to type float.
Simply change the type of your height and weight variables to float to fix this.
I think issue in scanf_s syntaxis, you ommited 3-rd argument, which is size of buffer in bytes. Try following:
scanf_s("%lf", &valueToGet, sizeof(double));
the drawback of the scanf() and printf() is that it requires very strict format, any mismatch between the control string and the argument can cause drastic error which makes your input or output make no sense at all. And that mistake is often made by beginners.
If you're using %f format specifier, then you must use float data type instead of double.
The problem is because:
format '%f' expects argument of type 'float*', but argument 2 has type 'double*'
There are two ways to handle this:
Either the variables should be float:
double height = 0; --> float height = 0;
double weight = 0; --> float weight = 0;
double bmi = 0; --> float bmi = 0;
or the format specifier should correspond to double.
scanf_s("%f", &height); --> scanf_s("%lf", &height);
scanf_s("%f", &weight); --> scanf_s("%lf", &weight);
printf("\nYour Body Mass Index stands at %f\n", bmi);
|
V
printf("\nYour Body Mass Index stands at %lf\n", bmi);

Resources