求数列的和
题目描述:
数列的定义如下:
数列的第一项为n,以后各项为前一项的平方根,求数列的前m项的和。
输入
输入数据有多组,每组占一行,由两个整数n(n<10000)和m(m<1000)组成,n和m的含义如前所述。
输出
对于每组输入数据,输出该数列的和,每个测试实例占一行,要求精度保留2位小数。
样例输入
81 4
2 2
样例输出
94.73
3.41
import sys for line in sys.stdin: if len(line.split(' ')) == 2: data,numb = [i.strip() for i in line.split(' ')] if data.isdigit() and numb.isdigit(): data,numb = int(data),int(numb) else: break if data < 0: break sum_b = [] total = 0 for i in range(numb): sum_b.append(data) data = data**0.5 for x in sum_b: total += x total = '%.2f'%total sys.stdout.write(total) else: break题目不难,主要是注意输入的特殊情况。
class Program { //数列求和 static void Main(string[] args) { //输入数据有多组,每组占一行,由两个整数n(n<10000)和m(m<1000)组成 Console.WriteLine("Please enter multiple sets of data, one for each group, consisting of two integers n (n < 10000) and m (m < 1000):"); string outs=""; while (true) { string s = Console.ReadLine(); if(string.IsNullOrEmpty(s)) { break; } else { int index = s.IndexOf(" "); int.TryParse(s.Substring(0, index),out int n); int.TryParse(s.Substring(index + 1), out int m); outs = outs + getSum(n, m)+" "; } } Console.WriteLine(outs); Console.ReadKey(); } static double getSum(int n, int m) { double sum = 0; double k = n; while (m > 0) { sum = sum + k; k = Math.Sqrt(k); m--; } return Math.Round(sum,2); } }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(sc.hasNext()){ int N =sc.nextInt(); //第一个数 int M = sc.nextInt(); //项数 double n = N; double sum = N; for(int i=1;i<M;i++) { n = Math.sqrt(n); sum += n; } System.out.println(String.format("%.2f",sum)); } } }