当前位置: 代码迷 >> J2SE >> ,帮忙看一下一个C语言函数翻译成java语言
  详细解决方案

,帮忙看一下一个C语言函数翻译成java语言

热度:104   发布时间:2016-04-24 01:09:10.0
求助,帮忙看一下一个C语言函数翻译成java语言
因为工作原因需要将一个C语言函数翻译成java语言,但是测试时报数组越界异常,下面贴代码

函数功能:根据传入的 9 位数字生成最后一位数字

C语言代码:

C/C++ code
#include "math.h"#include <string.h>#include  <stdlib.h>int  rint (double value){    return (int) (floor(value*2)-floor(value));}/*算法开始*/char* getCode(char* source) {    int i,len;  int aMod,sum,Wi;  char* myx=(char*)malloc(1);  int m_table[11]= {1,0,0,9,8,7,6,5,4,3,2};  int li_round,li_b,amod;  sum = 0;  len = strlen(source);  if(len==0){      return "-1";  }  for(i=1;i<len+1;i++){     double temp=exp(len-i+1);     double templog=log(2);      li_round=rint(exp((len-i+1)*log(2)));      Wi =(int) fmod(li_round,11);      li_b=source[i-1];      sum+=Wi*(li_b-'0');  }    amod=(int) fmod(sum,11);    if( amod == 2) {        myx = "X";    }    else {        aMod = m_table[amod];        /*把整型转化成字符*/        sprintf(myx,"%d", aMod);     }    return myx;}


java代码:

Java code
package com;public class Test {    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub        Test test = new Test();        System.out.println(test.getCode("072261793"));    }        private int rint (double value){        return (int)(Math.floor(value*2)-Math.floor(value));    }        private String getCode(String source){        int len = 0;        int sum = 0;        int Wi = 0;        String myx = "";        int[] m_table = {1,0,0,9,8,7,6,5,4,3,2};        int li_round = 0;        int li_b = 0;        int amod = 0;        sum = 0;        len = source.length();        if(len == 0){            return "-1";        }        for(int i = 1; i < len + 1;i++){            li_round = rint(Math.exp((len - i + 1) * Math.log(2)));            Wi = li_round/11;            li_b = source.charAt(i-1);            sum += Wi*(li_b - '0');        }        amod = sum/11;        if(amod == 2) {            myx = "X";        }        else {            myx = String.valueOf(m_table[amod]);        }        return myx;    }}


测试数据为:072261815,072261814


------解决方案--------------------
Wi = li_round/11; ->Wi = li_round%11;
amod = sum/11;->amod = sum%11;

看下对不对
------解决方案--------------------
哥们,fmod函数是返回余数吧?余数不是'/'是'%'吧?
  相关解决方案