Search code examples
clogic

Why is This Not Executing Correctly?


//A code to find Total of Electric Bill...

/* 
   Upto 100 Units - Rs 5 pu
   upto 200 units - Rs 5.5 pu
   upto 500 units - Rs 6.5 pu
   above 500 units - Rs 7 pu
*/

#include<stdio.h>
int
main ()
{
  int a;
  float b=0.0;
  printf ("Enter Your Consumption in Units: ");
  scanf ("%d", &a);
  if (a > 0)
    b=b+(a*5);
  if (a > 100)
    b=b+((a-100)*5.5);
  if (a > 200)
    b=b+((a - 200) * 6.5);
  if (a>500)
    b=b+((a - 500) * 7);
  printf("\n Your Bill is Rs. %f",b);
  return 0;
}

On giving 750 as Input, the expected answer is 4750, but it is showing 12650. also What would be a smarter method of doing this rather than using and and operators within each if statement?


Solution

  • With a equal 750 all if-statements will be true so your code will calculate 750 x 5 + (750-100) x 5.5 + (750-200) x 6.5 + (750-500) x 7 which is not what you want.

    You could change the order of the if-statements and reduce a with the amount paid so far.

    To keep it in the spirit of your code, it could look like:

      if (a>500)
      {
        b=b+((a - 500) * 7);
        a = 500;
      }
    
      if (a > 200)
      {
        b=b+((a - 200) * 6.5);
        a = 200;
      }
    
      if (a > 100)
      {
        b=b+((a-100)*5.5);
        a = 100;
      }
      
      b=b+(a*5);
    

    A more "generic" and easier to maintain approach could be:

    struct price_range
    {
        unsigned limit;
        double price;
    };
    
    const struct price_range pr[] =
    {
        {  0, 5.0},
        {100, 5.5},
        {200, 6.5},
        {500, 7.0}
    };    
    
    double calculate_price(unsigned amount)
    {
        size_t i = sizeof pr / sizeof pr[0];
        double p = 0;    
        do
        {
            --i;
            if (amount > pr[i].limit)
            {
                p += (amount - pr[i].limit) * pr[i].price;
                amount = pr[i].limit;
            }
        } while (i > 0);
        return p;
    }