Ruby内联-返回双精度值 [英] Ruby Inline - Returning Double Values

查看:247
本文介绍了Ruby内联-返回双精度值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

上面的示例代码显示0.我希望它能打印1.0.

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

推荐答案

使用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); /* <------------- */
    }            
  }'

  • 不要直接返回0.0.
  • 请勿使用VALUE存储C数值.
    • Don't return 0.0 directly.
    • Don't use VALUE to store C numeric values.
    • 这篇关于Ruby内联-返回双精度值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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