jh365
jh365

Reputation: 65

I keep getting 0 as the value of this variable

I'm trying to write this program to calculate simple interest on a deposit. It's supposed to add the interest money onto the original deposit.

But it keeps making variable "rate" 0 which is why when I run it, the result is 0. Any help is appreciated.

  #include <stdio.h>

int main(void){

    double d;
    double rate;
    double y;
    double final;
    int x;

    printf("Enter the deposit: ");
    scanf("%d", &d);

    printf("Enter the interest rate (0-100): ");
    scanf("%d", &rate);

    printf("Enter the number of years: ");
    scanf("%i", &x);

    rate = rate / 100;

    y = d * rate * x;

    final = d + y;


    printf("After %i number of years, the deposit in the savings account is now %d", x, rate);

}

Upvotes: 0

Views: 110

Answers (1)

For double variables you need to read them using the specifier %lf:

scanf("%lf", &d);

same for rate:

scanf("%lf", &rate);

C99 7.19.6.2 p 11 (fscanf)

l (ell) (...) following a, A, e, E, f, F, g, or G conversion specifier applies to an argument with type pointer to double;


As pointed by @WeatherVane in comment, you need to provide the correct conversion specifier to the corresponding argument or the behavior of your program will be undefined:

C99 7.19.6.1 p 9 (fprintf)

If a conversion specification is invalid, the behavior is undefined.248) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

For printf() the argument rate should have a conversion specifier %f:

printf("After %i number of years, the deposit in the savings account is now %f", x, rate);

C99 7.19.6.1 p 8 (fprintf)

f,F A double argument representing a floating-point number

Upvotes: 7

Related Questions