尾递归函数,用于计算数组中大于平均值的所有数字 [英] Tail-recursive function to count all numbers larger than average in an array

查看:150
本文介绍了尾递归函数,用于计算数组中大于平均值的所有数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个计算平均值的函数,并返回大于平均值的值。例如,传递{4,5,12,17}的数组应返回2(因为12和17大于平均值9.5)。到目前为止,我编写了函数来返回平均值,但是如何计算大于平均值的数字并保持尾递归?

以下是平均函数。



我的尝试:



I need to make a function that calculates the average and return the number of values larger than the average. For example, passing an array of {4, 5, 12, 17} should return 2 (because 12 and 17 are larger than the average 9.5). So far I wrote the function to return the average, but how can I make it count the numbers larger than the average and keep it tail-recursive?
Below is the average function.

What I have tried:

int TAvg(int* a, int size, int acc=0, int num=0){ //acc is the sum so far, num is the number of all elements
if (size == 0){ 
    return (acc / num); 
}
return TAvg(a, size - 1, acc+a[size-1], num+1);}

推荐答案

It听起来像是作业...



要做:

1.计算平均递归。

2。通过展开递归计数上面的平均值。
It sounds like homework...

To do:
1. calculate the average recursive.
2. by unwinding the recursion count the above average.


我们不做你的HomeWork。

HomeWork不会测试你的技能,乞求别人做你的工作,它将帮助您的老师检查您对所学课程的理解以及您应用它们时遇到的问题。

你的任何失败都会帮助你的老师发现你的弱点并设定补救措施。

所以,试一试,重读你的课程并开始工作。如果您遇到特定问题,请显示您的代码并解释这个问题,我们可能会提供帮助。



除非您正在学习递归,否则我建议您不要使用它对于这种功能。因为递归不会使编写更简单,编译器可能会重写为循环,如果不是,则是一种系统滥用。

We do not do your HomeWork.
HomeWork is not set to test your skills at begging other people to do your work, it is set to help your teacher to check your understanding of the courses you have taken and also the problems you have at applying them.
Any failure of you will help your teacher spot your weaknesses and set remedial actions.
So, give it a try, reread your lessons and start working. If you are stuck on a specific problem, show your code and explain this exact problem, we might help.

Unless you are studying recursion, I recommend to not use it for this kind of function. Because recursion do not make the writing simpler, the compiler is likely to rewrite as a loop, and if not, it is a kind of system abuse.
引用:

但是如何让它计算大于平均值的数字并保持尾递归?

but how can I make it count the numbers larger than the average and keep it tail-recursive?

简短回答,你不能。只是因为你需要之前开始计算。

Short answer, you can't. Simply because you need the average before starting to count.


这篇关于尾递归函数,用于计算数组中大于平均值的所有数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆