AviG
AviG

Reputation: 392

Why is my C program to do simple depreciation not working?

I am trying to write a program in C to calculate a salvage value after depreciation of something. However, in when I run this:

int main(int argc, char* argv){
    printf("enter the purchase price, years of service, annual depreciation:\n");
    double purchasePrice, yearsOfService, annualDep;
    scanf("%d %d %d", &purchasePrice, &yearsOfService, &annualDep);
    printf("purchase price is %d dollars\n", purchasePrice);
    printf("years of service is %d years\n", yearsOfService);
    printf("annual depreciation is %d dollars\n", annualDep);
    double salvageValue = purchasePrice - (yearsOfService * annualDep);
    printf("The salvage value of the item is %d", salvageValue);

    return 0;
}

it prints out the purchasePrice instead of what the salvageValue should be. What is going on?

Upvotes: 2

Views: 165

Answers (1)

bool3max
bool3max

Reputation: 2865

Replace your scanf call with:

scanf("%lf %lf %lf", &purchasePrice, &yearsOfService, &annualDep);

scanf requires that all passed pointers match the types of the conversion specifiers (and vice versa). You're passing pointers to doubles, and the correct conversion specifier is %lf.

From the scanf manpage:

l indicates either that the conversion will be one of d, i, o, u, x, X, or n and the next pointer is a pointer to a long int or unsigned long int (rather than int), or that the conversion will be one of e, f, or g and the next pointer is a pointer to double (rather than float). Specifying two l characters is equivalent to L. If used with %c or %s, the corresponding parameter is considered as a pointer to a wide character or wide-character string respectively.

(emphasis mine)

Upvotes: 4

Related Questions