Search code examples
cdoubleformat-specifiersconversion-specifier

I have written a code to convert from Celisius to Fahrenheit but the output is too huge


The code is:

#include <stdio.h>
#include <stdlib.h>

int main() {
    double C, F;
    printf("Enter the temperature in Celisius: ");
    scanf("%f", &C);
    F = 32 + (C * (180.0 / 100.0));
    printf("%f C = %f F\n", C, F);
    system("pause");
    return 0;
}

The output is:

Enter the temperature in Celisius: 100
-92559604910177974000000000000000000000000000000000000000000000.000000 C = -166607288838320360000000000000000000000000000000000000000000000.000000 F


Solution

  • You got wrong conversion specifier there with double for scanf(). You need to use

      scanf("%lf", &C);
    

    To add the relevant quote, from C11, chapter §7.21.6.2

    l (ell)

    Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an argument with type pointer to long int or unsigned long int; that a following a, A, e, E, f, F, g, or G conversion specifier applies to an argument with type pointer to double; or that a following c, s, or [ conversion specifier applies to an argument with type pointer to wchar_t.

    That said, you must check the return value of scanf() to ensure the success of the call. Otherwise, you'll end up using the value of an uninitialized variable.