游客 Signup | Login
中文 | En

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" />

Input

Output

Examples

Input

10

Output

s=1.417566

Solution 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;
}

Solution 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;
}
Time Limit 1 second
Memory Limit 128 MB
Discuss Stats
上一题 下一题