1291 - 2011年下半年浙江省高等学校计算机等级考试-编程题2

按下面要求编写程序:

1)定义函数f(n)计算n+(n+1)+…+(2n-1),函数返回值类型是double

    (2)定义函数main(),输入正整数n,计算并输出下列算式的值。要求调用函数f(n)计算n+(n+1)+…+(2n-1)


<img src="http://tk.hustoj.com:80/upload/pimg1337_1.png" alt="" height="46" width="399" />

题目输入

题目输出

输入/输出样例

题目输入

10

题目输出

s=1.417566

C语言解答

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int f(a)
{
    int i,y=0;
    for(i=a;i<a*2;i++)
    {
    	y=y+i;
    }
    return y;
}
int main(int argc, char *argv[]) {
	int n,i;
	double s=0;
	scanf("%d",&n);
	for(i=1;i<n+1;i++)
	{
		s=s+1.0/f(i);
	}
	printf("s=%f",s);
	return 0;
}

C++解答

#include <iostream>
#include <iomanip>
using namespace std;

double fun(int x);

int main()
{
double sum;int n;
cin>>n;
for(int i=1;i<=n;i++)
{
sum+=fun(i);
}
cout<<"s="<<fixed<<setprecision(6)<<sum;
}

double fun(int x)
{
int y=(x+2*x-1)*x/2;
double z=1/(double)y;
return z;
}
时间限制 1 秒
内存限制 128 MB
讨论 统计
上一题 下一题