-4

I'd like to apologize ahead of time if this is a dumb question, since I'm just a bit of a beginner with C. This exercise tells you to create a program that prints a conversion chart of Fahrenheit - Celsius (Though I'm doing it the other way around) with the use of a function. I looked up the solution (http://www.eng.uerj.br/~fariasol/disciplinas/LABPROG/C_language/Kernighan_and_Ritchie/solved-exercises/solved-exercises.html/krx115.html), and was wondering whether or not I could do the same in a different way/without explicitly stating "upper", "lower", and "step". This is what I came up with:

 #include <stdio.h>

    int conv(int cel, int fahr);

main() {
    int c, f;
    f = 0;
    for (c = 0; c <= 100; c = c + 5) {
            printf("%d\t%d\n", c, conv(c, f));
    }
}





int conv(int cel, int fahr)
{
        fahr = (fahr-32) * (5/9);
        return fahr;
}

However, this just prints a column of 0 to 100 and a column of all 0's. What am I doing wrong?

2 Answers2

1

You need to declare your variables of type float or double . You get 0 always because in this expression -

fahr = (fahr-32) * (5/9);

5/9 in integer division is 0 and whole value is 0 (due to multiplication with 0) .

Also as mention in comment , expression above should be -

 far=cel*(9/5)+32                   // convert  Celsius to fahrenheit

according to formula to calculate fahrenheit

ameyCU
  • 16,489
  • 2
  • 26
  • 41
1

You have done an integer division with (5/9) which evaluates to 0. It's also unclear which direction you are converting, so this example converts both ways and prints a table.

#include <stdio.h>

int convF2C(int fahr)
{
    return (fahr - 32) * 5 / 9;                 // multiplies before division
}

int convC2F(int cent)
{
    return 32 + cent * 9 / 5;                   // multiplies before division
}

int main(void)
{
    int n;
    printf("Temp\tCent\tFahr\n");
    for(n=0; n<=200; n+=10)
        printf("%d\t%d\t%d\n", n, convF2C(n), convC2F(n));
    return 0;
}

Program output:

Temp    Cent    Fahr
0       -17     32
10      -12     50
20      -6      68
30      -1      86
40      4       104
50      10      122
60      15      140
70      21      158
80      26      176
90      32      194
100     37      212
110     43      230
120     48      248
130     54      266
140     60      284
150     65      302
160     71      320
170     76      338
180     82      356
190     87      374
200     93      392
Weather Vane
  • 33,872
  • 7
  • 36
  • 56