Search code examples
cfunctionwhile-loopnested-if

Why my while loop is fail to execute after one time?


Below is my program

void metertofeet(double);
void gramtopounds(double);
void celsiustofahren(double);
int main(void)
{
    int n,i=0;
    char unit;
    double value;
    scanf("%d",&n);
    while(i<n)
    {
        i++;
        scanf("%lf %s",&value,&unit);
        if(unit=='m')
         metertofeet(value);
        if(unit=='g')
           gramtopounds(value);
        if(unit=='c')
           celsiustofahren(value);
    }
    return 0;
}
void metertofeet(double v1)
{
  double F;
  F=3.2808*v1;
  printf("%.6lf ft\n",F);
}
void gramtopounds(double v2)
{
    double P;
    P =  0.002205*v2;
    printf("%.6lf lbs\n",P);
}
void celsiustofahren(double v3)
{
    double Fh;
    Fh=32 + (1.8*v3);
    printf("%.6lf f\n",Fh);
}

This is a program that converts meter to feet, gram to pounds, and celsius to Fahrenheit. Based on the number of conversions (i.e) value of n When the execution happens, inside the while loop only one-time input is asked. And loop fails after even though my value of i is not exceeded n


Solution

  • unit is a character variable. %s specifies a string. Make it as %c as in scanf("%lf %c",&value,&unit);.