Search code examples
cif-statementuser-defined-functionsequationudf

Else if option 3 does not produce answer...what did I do wrong?


The program runs but I can't figure out why the function within the third else if statement doesn't return an accurate value. Thank you for the help in
advance.

finaltemp = newtemp(t, choice);

printf("\nThe converted temperature is: %f", finaltemp);

return(0);
}

double newtemp(double a, double b)
{
double result;
if (b==1)
  {
    result = (a-(273.15));
  }
if (b==2)
  {
    result = (a+(273.15));
  }
if (b==3)
  {
    result = (((5/9)*(a))-32);
  }
if (b==4)
  {
    result = (((9/5)*(a))+32);
  }
if (b==5)
  {
    result = (((9/5)*(a))-459.67);
  }
if (b==6)
  {
    result = ((a+459.67)*(9/5));
  }

 return(result);
 }

Solution

  • You're performing integer division, not floating point division.

    The expression (5/9) divides two int values, so the result is an int, specifically 0. You need to use floating point constants to force floating point division.

    if (b==3)
      {
        result = (((5.0/9.0)*(a))-32);
      }
    if (b==4)
      {
        result = (((9.0/5.0)*(a))+32);
      }
    if (b==5)
      {
        result = (((9.0/5.0)*(a))-459.67);
      }
    if (b==6)
      {
        result = ((a+459.67)*(9.0/5.0));
      }