zl程序教程

您现在的位置是:首页 >  大数据

当前栏目

习题 3.1 假如我国国民生产总值的年增长率为9%,计算10年后我国国民生产总值与现在相比增长多少百分比。

计算 10 多少 增长 习题 现在 3.1 我国
2023-09-14 09:06:57 时间

C程序设计 (第四版) 谭浩强 习题3.1 个人设计

习题 3.1 假如我国国民生产总值的年增长率为9%,计算10年后我国国民生产总值与现在相比增长多少百分比。计算公式为 p = (1 + r)^n,r为年增长率,n为年数,p为与现在相比的倍数

代码块

方法1:(直接公式计算)

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
    double p, r = 0.09;    //定义增长倍数,年增长率
    int n = 10;            //定义年数
    p = pow(1+r, n);       //增长倍数公式
    printf("%lf\n", p);
    system("pause");
    return 0;
}

方法2:(利用函数的模块化设计)

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double growth(double rat, int year);   //定义增长倍数函数
int main()
{
	double r = 0.09;
	int n = 10;
	printf("%lf\n", growth(r, n));
	system("pause");
	return 0;
}
//增长倍数函数
double growth(double rat, int year)
{
	return pow(1+rat, year);
}

方法3:(动态分配内存)

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void input(double *gr, double *y);
void p(double gr, double y);
int main()
{
	double *growth_rate=(double*)malloc(sizeof(double));
	double *year=(double*)malloc(sizeof(double));
	input(growth_rate, year);
	p(*growth_rate, *year);
	system("pause");
	return 0;
}
void input(double *gr, double *y)
{
	printf("Enter growth rate: ");
	scanf("%lf", gr);
	printf("Enter year: ");
	scanf("%lf", y);
}
void p(double gr, double y)
{
	double p;
	p=pow((1+gr), y);
	printf("result: %.3lf\n", p);
}