加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

端口ruby解决方案C

发布时间:2020-12-17 04:33:28 所属栏目:百科 来源:网络整理
导读:在C中有没有办法做到这一点,尤其是范围部分. answer = (0..999).select { |a| a%3 ==0 || a%5==0 }puts answer.inject { |sum,n| sum+n } 我已经创建了自己的c解决方案,但使用了更标准的for循环,并想知道是否有更酷的方法来做到这一点? 解决方法 模板元编程
在C中有没有办法做到这一点,尤其是范围部分.
answer = (0..999).select { |a| a%3 ==0 || a%5==0 }
puts answer.inject { |sum,n| sum+n }

我已经创建了自己的c解决方案,但使用了更标准的for循环,并想知道是否有更酷的方法来做到这一点?

解决方法

模板元编程解决方案:

以下假设范围的下限为0.

template <int N>
struct sum
{
  static const int value = sum<N-1>::value + (N % 3 == 0 || N % 5 == 0 ? N : 0);
};

template <>
struct sum<0>
{
  static const int value = 0;
};

int main(int argc,char** argv)
{
  int n = sum<999>::value;
  return 0;
}

以下内容允许您指定一系列数字(例如0-999,20-400).我不是模板元编程的大师,所以我想不出一个更清洁的解决方案(我这样做是为了我自己的利益和实践).

template <int N,int Upper,bool IsLast>
struct sum_range_helper
{
  static const int value = (N % 3 == 0 || N % 5 == 0 ? N : 0) + sum_range_helper<N + 1,Upper,N + 1 == Upper>::value;
};

template <int N,int Upper>
struct sum_range_helper<N,true>
{
  static const int value = (N % 3 == 0 || N % 5 == 0 ? N : 0);
};

template <int Lower,int Upper>
struct sum_range
{
  static const int value = sum_range_helper<Lower,Lower == Upper>::value;
};

int main(int argc,char** argv)
{
  int n = sum_range<0,999>::value;
  return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读