C – 简单的数学论证不起作用?

我只想用一个相对简单的公式来计算10年的金额。 我可以输入我的所有变量,但我怀疑我的amount

 #include  #include  int main(){ double amount; /* amount on deposit */ double principal; /* what's the principal */ double rate; /* annual interest rate */ int year; /* year placeholder and no. of total years */ int yearNo; printf("What is the principal? "); scanf("%d", &principal); printf("What is the rate (in decimal)? "); scanf("%lf", &rate); printf("How many years? "); scanf("%d", &yearNo); printf("%4s%21s\n", "Year", "Amount on deposit"); /* calculate the amount on deposit for each of ten years */ for (year = 1; year <= yearNo; year++ ){ amount = principal * pow(1.0 + rate, year); printf("%4d%21.2f\n", year, amount); } return 0; } 

我是C的新手,但我正在读一本书中的例子。 这本书“硬编码”数字,我正在努力学习如何使用用户的输入来计算数据。

我是否正确地认为这是我的amount或者我最后用%f来引用它?

谢谢你的任何想法:)

对于scanf()系列函数, %d用于int%lf用于double

首先要做的是确保为编译器启用了警告。 一些编译器(GCC,Clang)报告这样的格式错误。

接下来要做的是打印您阅读的值。 当你看到垃圾出来时你刚读到的值,你知道有问题。

之后,您检查转换是否成功:

 if (scanf("%lf", &principal) != 1) …oops! input error or EOF…