【codewars-9】预测年龄

My grandfather always predicted how old people would get, and right before he passed away he revealed his secret!

In honor of my grandfather’s memory we will write a function using his formula!

  • Take a list of ages when each of your great-grandparent died.
  • Multiply each number by itself.
  • Add them all together.
  • Take the square root of the result.
  • Divide by two.
Example
predictAge(65, 60, 75, 55, 60, 63, 64, 45) === 86

Note: the result should be rounded down to the nearest integer.

分析
此题目难点不在求解的思路上. 而是面对多个参数时如何利用语言本身的语法特性来简化代码.

// 最笨的解法:
#include <math.h>
int predictAge(int age1, int age2, int age3, int age4, int age5, int age6, int age7, int age8)
{
  return sqrt(age1*age1+age2*age2+age3*age3+age4*age4+age5*age5+age6*age6+age7*age7+age8*age8)/2;
}

更好的解法

重点:

  • std::array<类型, 个数> 来替代C数组, 以此获取使用模板的能力
  • typename后加省略号
  • 类型名后加省略号
  • sizeof...()
  • 对后续无须改变的变量一律用const修饰
  • std::common_type_t<T...> 返回公共最小父类型
  • std::accumulate 对数组中的值进行累加
#include <numeric> // std::accumulate()
#include <cmath> // std::sqrt()
#include <array> // std::array
 
template <typename ... T>
int predictAge(const T ...ages)
{
  const std::array<std::common_type_t<T...>, sizeof...(T)> all_ages = { (ages*ages)... };
  
  const int sum = { std::accumulate(all_ages.begin(), all_ages.end(), 0) }; // 初始值为0
  
  const auto squared = std::sqrt(sum) / 2;
  
  return squared;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值