having trouble using % in a vat calculator only getting inf and -inf in results

Viewed 45
#include <stdio.h>

int main(void)
{
    float price, vat, vatless, vatprice;
    int vatpercentage;

    printf("Enter the price of the item:\n ");
    scanf_s("%f", &price);

    printf("what is the current vat:  \n");
    scanf_s("%d", &vatpercentage);

    vatpercentage = (float) (vatpercentage / 100);
    vat = (float) (vatpercentage * vatpercentage);
    
    vatless = price / vat;

    vatprice = price - vatless;

    printf("Total = %.2f\n", price);
    printf("Your vatless price is %.2f\n", vatless);
    printf("your vatprice is %.2f\n", vatprice);

    return 0;
}

Hello trying to make a vat calculator but I can't really figure out why I'm only getting inf and - inf when I try this code.

2 Answers

vatpercentage is an int, so the division vatpercentage / 100 is done as integer division. Define it as a float and you should be OK.

Simplicity is beneficial... I am lost in the tangle, computing values for 5 different variables with similar names.

Try this:

int main() {
    double price;
    printf( "Enter the price: " );
    scanf( "%lf", &price );

    int vat;
    printf( "Enter the VAT %%: ");
    scanf( "%d", &vat );

    double base = price * 100 / ( 100 + vat );
    printf( "Total%9.2lf\n", price );
    printf( "VAT  %9.2lf (%d%%)\n", price - base, vat );
    printf( "Base %9.2lf\n", base );

    return 0;
}

Output

Enter the price: 68.95
Enter the VAT %: 13
Total    68.95
VAT       7.93 (13%)
Base     61.02

Error checking and validating the input have been omitted for brevity.

"Floating point" will (usually) be a close approximation of what we humans regard as "integer values". There may be values that are shown as "5.00", but, internally, the value is "4.9998". The user is warned and, with the inclusion of "math.h", computed floating point values should be rounded appropriately.

I don't have experience with "VAT", but I think these 3 variables are computing what you are seeking. Please let me know if this is wrong and I will delete this answer as quickly as possible.

Related