Conversion from Farenheit to Centigrade always gives zero

Asked

Viewed 1,217 times

2

This is the exercise:

1.12.3. Conversion from Farenheit degrees to centigrade is obtained by 5 C = 9(F - 32)
Make an algorithm that calculates and writes a table of centigrade as a function of Farenheit degrees, ranging from 50 to 150 of 1 in 1.

I made my code like this:

#include <stdio.h>

int main () {

    float F, C;

    for (F=50; F<=150; F++) {
        printf("--------------------------------\n");
        printf("Farenheit = %.0f",F);
        C = (5 / 9) * (F - 32);
        printf("\nConvertido para centígrados = %.2f\n",C);
    }
    printf("\n");
    return 0;
}

I did something wrong in the code or it’s compiler error?

1 answer

5


The "never" error is from the compiler, it is always from the programmer.

The problem is that you are mixing numbers with floating point and integer. How much is 5 divided by 9? Gives 0, then multiply by anything gives 0.

I took the opportunity to simplify a little:

#include <stdio.h>

int main () {
    for (float F = 50; F <= 150; F++) {
        printf("--------------------------------\n");
        printf("Farenheit = %.0f\nConvertido para centígrados = %.2f\n", F, (5.0f / 9.0f) * (F - 32.0f));
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • GCC does not recognize this syntax for (float F = 50 ...) :(

  • @cat Only if it is a very old GCC. Still use -std=c99. It is a complete nonsense to continue using C of the 80’s that uses a practice considered bad today.

  • My version is gcc (tdm-2) 4.8.1 Which version can I use? The -std=c99 is a flag? It would be possible to enable this option in code-Blocks?

  • Ah, it has these different distributions. It’s a flag, has the control line function yes, this should be: http://stackoverflow.com/q/33208733/221800

  • I created a new flag -std=gnu99 in Build options > Others options and it worked here :D

  • or, only declare the variable F at the beginning of the function, as and did for more than 40 years.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.