我一直得到 0 作为这个变量的值

I keep getting 0 as the value of this variable

我正在尝试编写这个程序来计算存款的单利。它应该把利息加到原来的存款上。

但它一直使变量 "rate" 为 0,这就是为什么当我 运行 它时,结果为 0。感谢任何帮助。

  #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);

}

对于 double 变量,您需要使用说明符 %lf:

来读取它们
scanf("%lf", &d);

rate 相同:

scanf("%lf", &rate);

C99 7.19.6.2 第 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;


正如@WeatherVane 在评论中指出的那样,您需要为相应的参数提供正确的转换说明符,否则程序的行为将是未定义的:

C99 7.19.6.1 第 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.

对于 printf() 参数 rate 应该有一个转换说明符 %f:

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

C99 7.19.6.1 第 8 页 (fprintf)

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