我正在尝试编写这个程序来计算存款的简单利息.它应该将利息金额加到原始存款上.
但它继续使变量"速率"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);
}
Run Code Online (Sandbox Code Playgroud)
对于double变量,您需要使用说明符读取它们%lf:
scanf("%lf", &d);
Run Code Online (Sandbox Code Playgroud)
同样的rate:
scanf("%lf", &rate);
Run Code Online (Sandbox Code Playgroud)
C99 7.19.6.2 p 11(fscanf)
l(a),a,e,E,fF,g或G转换说明符后面的(...)适用于类型指针为double的参数 ;
正如@WeatherVane在评论中指出的那样,您需要为相应的参数提供正确的转换说明符,否则程序的行为将是未定义的:
C99 7.19.6.1 p 9(fprintf)
如果转换规范是无效的,该行为是undefined.248)如果任何参数是不正确的类型为相应的转换规格,该行为是未定义的.
对于printf()参数rate应该有一个转换说明符%f:
printf("After %i number of years, the deposit in the savings account is now %f", x, rate);
Run Code Online (Sandbox Code Playgroud)
C99 7.19.6.1 p 8(fprintf)
f,FAdouble参数表示浮点数