已知今年的工业产值为100万元,产值增长率为从键盘输入,请编程计算工业产值过多少年可实现翻一番(即增加一倍)。
参考答案:用符号常量CURRENT表示今年的工业产值为100万元,用变量growRate表示产值增长率,用变量year表示产值翻番所需的年数,则计算年产值增长额的计算公式为:
output = output * (1 + growRate)
利用迭代法循环计算,直到output >= 2*CURRENT时为止。当output >= 2*CURRENT时,表示已实现产值翻番。此时,循环被执行的次数year即为产值翻番所需的年数。
**输入格式要求:"%lf" 提示信息:"Input grow rate:"
**输出格式要求:"When grow rate is %.0f%%, the output can be doubled after %d years.\n"
程序运行示例如下:
Input grow rate:0.08
When grow rate is 8%, the output can be doubled after 10 years.
#include <stdio.h>
#define CURRENT 100
main()
{
int year; /* 产值翻番所需年数 */
double growRate; /* 工业产值的增长率 */
double output; /* 工业总产值 */
printf("Input grow rate:");
scanf("%lf", &growRate);
output = CURRENT; /* 当年产值为100万元 */
for (year = 0; output < 2 * CURRENT; year++)
{
output = output * (1 + growRate);
}
printf("When grow rate is %.0f%%, the output can be doubled after %d years.\n", growRate * 100, year);
}