7-18 求平方根序列前N项和
作者 颜晖
单位 浙江大学
本题要求编写程序,计算平方根序列1+2+3+⋯的前N项之和。可包含头文件math.h
,并调用sqrt
函数求平方根。
输入格式:
输入在一行中给出一个正整数N。
输出格式:
在一行中按照“sum = S”的格式输出部分和的值S,精确到小数点后两位。题目保证计算结果不超过双精度范围。
输入样例:
10
输出样例:
sum = 22.47
C实现:
#include <stdio.h>
double A(int N){
double x = (double)N;
double s = 0;
if(N % 2 != 0){
s = - (1 + x) / (1 + 2 * x);
}else{
s = (1 + x) / (1 + 2 * x);
}
return s;
}
java实现:
import java.util.Scanner; public class a04 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); double result = sum(n); System.out.println("sum = " + String.format("%.2f", result)); } public static double sum(int n) { double result = 0.0; for (int i = 1; i <= n; i ++) { result += Math.sqrt(i); } return result; } }