Home > Blockchain >  how can i get this c program to output the Celsius value in the table
how can i get this c program to output the Celsius value in the table

Time:09-27

I am trying to create a conversion table using c programing language. I want to convert the temperature from -250 f to 250 in Celsius increment of 10. but I am not getting the Celsius output

#include <p18f458.h>
#include <stdio.h>

#pragma config WDT = OFF

#define LOWER -250 /* lower limit of table */
#define UPPER 250 /* upper limit */
#define STEP 10 /* step size */

void main(void)
{
    int fh, cel;
    cel = (fh - 32) * 5 / 9;

    for (fh = LOWER; fh <= UPPER; fh = fh   STEP)
        printf("%d \t   %6.1f\n", fh, cel);

    while(1);  
} 
 Fahrenheit      Celsius

 -250      
-240       
-230       
-220       
-210       
-200       
-190       
-180       
-170       
-160       
-150       
-140       
-130       
-120       
-110 .......

CodePudding user response:

Recalculate each time

Use floating point math


//     dddd123456789012ffffff
puts(" Fahrenheit      Celsius");

// cel = (fh - 32) * 5 / 9;

for (fh = LOWER; fh <= UPPER; fh = fh   STEP) {
  double cel = (fh - 32.0) * 5.0 / 9.0;
  printf(" M            %6.1f\n", fh, cel);
}

CodePudding user response:

As others have noted: 1) use floating point to avoid integer division and truncation errors, 2) recalculate values inside the loop.

It would be a shame to miss this opportunity to produce parallel tables of F->C and also C->F for the given range.

#define LOWER  -250
#define UPPER   250
#define STEP     10

int main() {
    puts( "    F        C             C        F" );

    for( int i = UPPER; i >= LOWER; i -= STEP ) {
        printf( "%6.0f   %6.0f", (double)i, (i - 32.0) * 5.0 / 9.0 );
        printf( "        " );
        printf( "%6.0f   %6.0f\n", (double)i, i * 9.0 / 5.0   32.0 );
    }

    return 0;
}
    F        C             C        F
   250      121           250      482
   240      116           240      464
   230      110           230      446
   220      104           220      428
   210       99           210      410
   200       93           200      392
// omitted...
  -220     -140          -220     -364
  -230     -146          -230     -382
  -240     -151          -240     -400
  -250     -157          -250     -418

Ordinary mercury thermometers condition people to expect warmer temperatures at the top, and cooler temperatures 'below'... This table reverses the sequence presented in the OP to conform to people's expectations.

CodePudding user response:

cel = (fh - 32) * 5 / 9;

Why is this outside the loop? Do you want it to be to be calculated only once?

  • Related