Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading