lundi 12 juin 2017

calculating amount based on uneven ranges in C

I was going through previous paper questions and found a question that requires me to produce a bill based on the number of units(of electricity) each customer have consumed. there's a table given instructing how the calculation is done. I already made the program in a very basic way using if else statements. I want to know if there is a better approach to this than using if else. maybe loops ? I tried using loops but its impractical to me since the ranges are not constant. This is a screenshot of a portion of that question.Question Screenshot

The function I created to calculate is given below.

void findBill(int table[],float ar[],int size)
{
int i; 
float bill;
for(i=0; i<7 ; i++)
{
    if((table[i]>=0)&&(table[i]<=5))
    {   bill=table[i]*3.0;
    }
    else if((table[i]>=6)&&(table[i]<=10))
    {   bill=5*3.0+(table[i]-5)*7.0;
    }
    else if((table[i]>=11)&&(table[i]<=15))
    {   bill=5*3.0+5*7.0+(table[i]-10)*15.0;
    }
    else if((table[i]>=16)&&(table[i]<=20))
    {   bill=5*3.0+5*7.0+5*15.0+(table[i]-15)*30.0;
    }
    else if((table[i]>=21)&&(table[i]<=25))
    {   bill=5*3.0+5*7.0+5*15.0+5*30.0+(table[i]-20)*50.0;
    }
    else if((table[i]>=26)&&(table[i]<=30))
    {   bill=5*3.0+5*7.0+5*15.0+5*30.0+5*50.0+(table[i]-25)*75.0;
    }
    else if((table[i]>=31)&&(table[i]<=40))
    {   bill=5*3.0+5*7.0+5*15.0+5*30.0+5*50.0+5*75.0+(table[i]-30)*90.0;
    }
    else if((table[i]>=41)&&(table[i]<=50))
    {   bill=5*3.0+5*7.0+5*15.0+5*30.0+5*50.0+5*75.0+10*90.0+(table[i]-40)*105.0;
    }
    else if((table[i]>=51)&&(table[i]<=75))
    {   bill=5*3.0+5*7.0+5*15.0+5*30.0+5*50.0+5*75.0+10*90.0+10*105.0+(table[i]-50)*110.0;
    }
    else if(table[i]>75)
    {   bill=5*3.0+5*7.0+5*15.0+5*30.0+5*50.0+5*75.0+10*90.0+10*105.0+25*110.0+(table[i]-75)*120.0;
    }

    ar[i]=bill; 
}

}

Even though this works i feel that this is bad coding, what if there were 100 ranges. Please suggest me another easier way to do this rather than writing simple if else statements.

P.S : I am a beginner, so please be kind enough to suggest answers using stdio.h in C.

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire