-2

I have

float AddVat(float price, int category)
float total_price=0;

I need write function that calculate and return total price including VAT (use switch/case without scanf, for beginners)

VAT category:
1 - 20%
2 - 20%
3 - 20%
4 - 15%
5 -  8%
6 -  0%

I tried multiplying the price by a percentage.

I want understand how to find solution.

Clifford
  • 88,407
  • 13
  • 85
  • 165
Viki
  • 1
  • 2

1 Answers1

1

If you want to return the price + vat you could do this:

float addVat(float price, int category) {
    float vat;
    switch(category) {
        case 1:
        case 2:
        case 3:
            vat = 0.20;
            break;
        case 4:
            vat = 0.15;
            break;
        case 5:
            vat = 0.08;
            break;
        case 6:
            vat = 0;
            break;
        default:
            // error
            return -1;
    }
    return (1 + vat) * price;
}

int main(void) {
    for(int category = 0; category < 8; category++)
        printf("%d %.2f\n", category, addVat(2, category));
}

and output:

0 -1.00
1 2.40
2 2.40
3 2.40
4 2.30
5 2.16
6 2.00
7 -1.00

I realize this is a school assignment but you should know that it's a bad idea to use float for money.

Value-Added Tax (VAT) works differently than a sales tax and we only implemented the latter here. Presumably this is a company so you need to deduct the vat they paid, and to figure out net liability. It's usually a flat rate etc.

Rate tables like your (category, vat percentage) tables are subject to change in the real-world, so you want it to be data not code. The first step is this:

float addVat(float price, int category) {
    category--;
    float vat[] = { 0.20, 0.20, 0.20, 0.15, 0.08, 0 };
    if(category < 0 || category >= sizeof(vat) / sizeof *vat) return -1;
    return (1 + vat[category]) * price;
}

The next step is then store the vat array in a database or file instead of in the array and then look it up at run-time when needed:

   float vatLookup(int category);

Category is modeled with an integer so your call the function like this:

  addVat(price, vat);

but that it's super easy to swap the arguments by mistake and your compiler will probably not even generate a warning:

  addVat(vat, price);

enum, constants, or a struct would be better choices for modeling the vat. Only the latter would play well with a run-time loading the data so maybe and change the lookup function:

   struct vat {
     float percent;
   };

   float addVat(float price, const struct vat *vat);
   struct vat *vatLookup(int category);

The call now becomes:

   addVat(2, vatLookup(2));

Finally, it's problematic to conflate the output and error domain like I did. Maybe refunds will be represented as negative values at some future point in time. See error handling in c for a discussion.

Allan Wind
  • 23,068
  • 5
  • 28
  • 38