Ruby Inline - Returning Double Values [closed]

烈酒焚心 提交于 2019-12-11 21:52:35

问题


require 'inline'

class InlineTest
  inline(:C) do |builder|
    builder.c '
      VALUE arr_distance(VALUE arr1, VALUE arr2){
         long arr1_len = RARRAY_LEN(arr1);
         long arr2_len = RARRAY_LEN(arr2);
         if(arr1_len == 0 || arr2_len == 0){
           return 0.0;
         }
         else{
           long i, j;
           int count = 0;
           VALUE *c_arr1 = RARRAY_PTR(arr1);
           VALUE *c_arr2 = RARRAY_PTR(arr2);
           for(i = 0; i < arr1_len; i++){
             for(j = 0; j < arr2_len; j++){
               if(rb_str_cmp(c_arr1[i], c_arr2[j]) == 0){
                 count++;
               }
             }
           }
           VALUE arr1_match = count/arr1_len;
           VALUE arr2_match = count/arr2_len;
           VALUE match_percent = (arr2_match * 10 + arr1_match) / 11.0;
           return match_percent; //This does not return double value.
        }
     }'
  end
end

p InlineTest.new.arr_distance(['1', '2', '3'], ['1', '2', '3']) # => 0

I use the above logic to compute my match percent.

Above example code prints 0. I expected it to print 1.0.


回答1:


Use DBL2NUM:

builder.c '
  VALUE arr_distance(VALUE arr1, VALUE arr2){            
      long arr1_len = RARRAY_LEN(arr1);
      long arr2_len = RARRAY_LEN(arr2);            
      if(arr1_len == 0 || arr2_len == 0){
        return DBL2NUM(0.0); /* <------------ */
      }
      else{
        long i, j;
        int count = 0;
        VALUE *c_arr1 = RARRAY_PTR(arr1);
        VALUE *c_arr2 = RARRAY_PTR(arr2);

        for(i = 0; i < arr1_len; i++){
          for(j = 0; j < arr2_len; j++){
            if(rb_str_cmp(c_arr1[i], c_arr2[j]) == 0){
              count++;
            }
          }
        }

        VALUE arr1_match = count/arr1_len;
        VALUE arr2_match = count/arr2_len;
        double match_percent = (arr2_match * 10 + arr1_match) / 11.0;
        return DBL2NUM(match_percent); /* <------------- */
    }            
  }'
  • Don't return 0.0 directly.
  • Don't use VALUE to store C numeric values.


来源:https://stackoverflow.com/questions/19830251/ruby-inline-returning-double-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!