-1
$\begingroup$

I cannot determine why the Celsius values in this code are producing rubbish values. (Look at second statement in the first for-loop).

CODE:

/* The program will output two columns with the temperature in degrees Fahrenhiet 
and equivalent temperature in degrees Celcius. The range will be 0 to 300 farenhiet in 
20 degree intervals. */

#include <stdio.h>

int main()

{
    double fahr[20], cel[20]; // there should be 16 values (300/20 + 1) in these arrays and a null zero. (total of 17 values)
                              // Doesn't hurt to make them a bit larger than necessary (i.e. 20 instead of 17 values)

    for (int i = 0; i < 16; i++)
    {
            fahr[i] = i*20; // Express Farhrenhiet as a linear function of i and iterate 
            cel[i] = (5 / 9) * (fahr[i] - 32); // Express Celcius as a linear function of fahr[i]
    }

    printf("Fahrenheit\tCelcius\n"); //printing the column headers 

    for (int j = 0; j < 16; j++)
    {
        printf("%.f", fahr[j]);
        printf("\t\t%.2f", cel[j]);
        printf("\n");
    }

    return 0;
}
$\endgroup$

closed as off-topic by David Richerby, Tom van der Zanden, Ran G., André Souza Lemos, Rick Decker Jun 10 '15 at 18:33

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions about software development or programming tools are off-topic here, but can be asked on Stack Overflow." – David Richerby, Tom van der Zanden, Ran G., André Souza Lemos, Rick Decker
If this question can be reworded to fit the rules in the help center, please edit the question.

1
$\begingroup$

The expression 5/9 (the second statement of first loop) will make an integer division, which will result in 0. You have to write 5.0/9 or 5/9.0 to get a double value as result.

$\endgroup$
  • $\begingroup$ Thank you. I didn't know that. Just to clarify the theory: Writing 5.0/9 or 5/9.0 (or even 5.0/9.0) ensures that I am diving by floating point values? And when ever I divide integers, I will get an integer value truncated? $\endgroup$ – Ryan J. Shrott Jun 10 '15 at 15:53
  • $\begingroup$ Exactly you can also write 5.0/9.0. Dividing numbers that are both integer will give to you only the division. E.g 18/5 will be 3 $\endgroup$ – atayenel Jun 10 '15 at 16:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.