0

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);
}
celeritas
  • 2,191
  • 1
  • 17
  • 28
KevinRandall
  • 51
  • 1
  • 1
  • 6

3 Answers3

1

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.
AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
0

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.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
0

You're reading a float (with %f) and yet you're storing it inside a double.

Either

  1. Change the type of fahrenheit to float
  2. Change your scanf call to `scanf("%lf", &fahrenheit);
SolarBear
  • 4,534
  • 4
  • 37
  • 53