端口ruby解决方案C

前端之家收集整理的这篇文章主要介绍了端口ruby解决方案C前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在C中有没有办法做到这一点,尤其是范围部分.
  1. answer = (0..999).select { |a| a%3 ==0 || a%5==0 }
  2. puts answer.inject { |sum,n| sum+n }

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

解决方法

模板元编程解决方案:

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

  1. template <int N>
  2. struct sum
  3. {
  4. static const int value = sum<N-1>::value + (N % 3 == 0 || N % 5 == 0 ? N : 0);
  5. };
  6.  
  7. template <>
  8. struct sum<0>
  9. {
  10. static const int value = 0;
  11. };
  12.  
  13. int main(int argc,char** argv)
  14. {
  15. int n = sum<999>::value;
  16. return 0;
  17. }

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

  1. template <int N,int Upper,bool IsLast>
  2. struct sum_range_helper
  3. {
  4. static const int value = (N % 3 == 0 || N % 5 == 0 ? N : 0) + sum_range_helper<N + 1,Upper,N + 1 == Upper>::value;
  5. };
  6.  
  7. template <int N,int Upper>
  8. struct sum_range_helper<N,true>
  9. {
  10. static const int value = (N % 3 == 0 || N % 5 == 0 ? N : 0);
  11. };
  12.  
  13. template <int Lower,int Upper>
  14. struct sum_range
  15. {
  16. static const int value = sum_range_helper<Lower,Lower == Upper>::value;
  17. };
  18.  
  19. int main(int argc,char** argv)
  20. {
  21. int n = sum_range<0,999>::value;
  22. return 0;
  23. }

猜你在找的Ruby相关文章