编写一个函数来计算C中一行的范围内的平方和 [英] Writing a function that calculates the sum of squares within a range in one line in C
问题描述
我的尝试
double sum_squares_from(double x, double n){
return n<=0 ? 0 : x*x + sum_squares_from((x+n-1)*(x+n-1),n-1);
}
我的教授不是使用循环,而是希望我们编写这样的函数... 练习要求的是一个函数sum_squares_from(),其中double x是起始数字,n是数字.例如,如果执行x = 2和n = 4,则得到2 * 2 + 3 * 3 + 4 * 4 + 5 * 5.如果n == 0,则返回零.
Instead of using loops my professor wants us to write functions like this... What the exercise asks for is a function sum_squares_from() with double x being the starting number and n is the number of number. For example if you do x = 2 and n = 4 you get 2*2+3*3+4*4+5*5. It returns zero if n == 0.
我的想法是,在我的示例中,我所拥有的基本上是x * x +(x + 1)(x + 1)+(x + 1 + 1)(x + 1 + 1)+(x + 1 + 1 +1)(x + 1 + 1 + 1)=(x + 0)(x + 0)+(x + 1)(x + 1)+(x + 2)(x + 2)+(x + 3 )(x + 3)=(x + n-1)^ 2重复n次,其中n每次递减1直到它变为零,然后将所有内容相加.
My thinking was that in my example what I have is basically x*x+(x+1)(x+1)+(x+1+1)(x+1+1)+(x+1+1+1)(x+1+1+1) = (x+0)(x+0)+(x+1)(x+1)+(x+2)(x+2)+(x+3)(x+3) = (x+n-1)^2 repeated n times where n gets decremented every time by one until it becomes zero and then you sum everything.
我做对了吗?
(如果我的教授似乎有点苛求...他不知不觉地以某种方式在脑海中做了这种事情.可怕的家伙)
(if my professor seems a bit demanding... he somehow does this sort of thing all in his head without auxiliary calculations. Scary guy)
推荐答案
也许是吗?
double sum_squares_from(double x, double n) {
return n <= 0 ? 0 : (x + n - 1) * (x + n - 1) + sum_squares_from(x, n - 1);
}
这篇关于编写一个函数来计算C中一行的范围内的平方和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!