Shasster
Shasster

Reputation: 13

Why does this program give me a miscalculation only on the first input?

This is my attempt at using a function to convert from Fahrenheit to Celsius in C. What has me puzzled is that it works for every input except the first one and I can't figure out why. If I remove the while loop and just leave whats inside the program works as expected but then I can only convert one value before having to run the program again.The first value entered is usually -16. something for me.

As a side note can anyone recommend a method to search for these types of questions when its kind of program specific?

    #include <stdio.h>

    float fToC(float far);

    int main()
    {
        int c;
        float far;
        while((c = getchar()) != EOF)
        {
        scanf("%f", &far);
        printf("%.2f\n", fToC(far));
        }
        return 0;
     }

    float fToC(float far)
    {
        float C;
        C = (5.0 / 9.0) * (far - 32.0);
        return C;
    }

Upvotes: 0

Views: 69

Answers (2)

hdante
hdante

Reputation: 8020

getchar() eats the first character and scanf() can't read it. Starting on the second iteration this is ok: the eaten character will be '\n', then ENTER key that scanf() does not read. On the first time, however, the character is an useful one: '-' when "-16" is typed. Solution: remove the getchar() and use a scanf parse format that skips white space: " %f".

Upvotes: 1

Nguai al
Nguai al

Reputation: 958

Is there a need for getchar()? Newline character (invisible character) is also considered as an input. It stays in the input buffer and gets assigned to far.

Skip getchar() and just enter far. scanf() returns 1 if appropriate input has entered. If an inappropriate input has entered like a letter, it will return 0 and simply wont go inside the loop.

    while((scanf("%f", &far) == 1))
    {
       printf( "far = %f\n", far);
       printf("%.2f\n", fToC(far));
    }

Upvotes: 3

Related Questions