1.1 等 比 数 列
1.1.1 题目内容
已知 q 与 n,求等比数列之和: 。
输入描述:
输入数据不多于 50 对,每对数据含有一个整数 n(1≤n≤20)、一个小数q(0<q<2)。
输出描述:
对于每组数据 n 和 q,计算其等比数列的和,精确到小数点后 3 位,每个计算结果应单独占一行。
输入样例
6 0.3 5 1.3
输出样例
1.428
12.756
直接做:
#include<iostream>
#include <cmath>
using namespace std;
int main()
{
cout.precision(3);
int n,i;
double q,sum;
while(cin>>n>>q)
{
for(i=0;i<=n;i++)
sum=sum+pow(q,i);
cout<<fixed<<sum<<endl;
sum=0.0; //重置为0
}
return 0;
}
1.1.2 提示
对于等比数列之和 ,有公式 ( q ≠ 1)。本例要求的等比数列,实际上是有 n +1项,且 =1。
另外,求 的函数是 pow(x,y),它需要“#include <cmath>”。
本题要求控制小数点后的位数,如果采用 C 语言的 printf 函数来输出,那么控制小数点后的位数形式为“printf("%*.*f", a);”,如“printf("%.3f\n",sum);”。如果采用 C++的 cout输出,那么先用“cout.precision(n);”来设定小数点后保留 n 位,然后,输出时加“fixed”参数,表明是定点输出。
#include <iostream>
#include <cmath>
using namespace std;
int main(int argc, char* argv[])
{
//定点输出小数点后 3 位;否则是输出有效数字 3 位
cout.precision(3);
int n;
double q,sum;
while(cin>>n>>q)
{
if(q==1)sum=1+n;
else
sum=(1-pow(q,n+1))/(1-q);
//使用 fixed,定点输出,即小数点后的精度是 3 位
cout<<fixed<<sum<<endl;
}
return 0;
}