Javascript编号到罗马转换

时间:2017-02-12 04:30:31

标签: javascript

我希望从Number转换为Roman(X,IV等)。

有人提出了这个解决方案,我正在通过解决方案,但即使我调试它也无法理解。

有人可以解释发生了什么吗?我只是想学习一些JS。

function convertToRoman(num) {

  var roman =  {"M" :1000, "CM":900, "D":500, "CD":400, "C":100, "XC":90, "L":50, "XL":40, "X":10, "IX":9, "V":5, "IV":4, "I":1};
    str = "";

  for (var i in roman ) {
    var q = Math.floor(num / roman[i]); //Why?
    num -= q * roman[i]; //Why?
    str += i.repeat(q); //Why?
  }

  return str;

}

2 个答案:

答案 0 :(得分:2)

描述

以下评论中描述的代码。

// this is a function declaration
// with a parameter called num
function convertToRoman(num) {
  // this is an object, being used as a lookup
  var roman =  {"M" :1000, "CM":900, "D":500, "CD":400, "C":100, "XC":90, "L":50, "XL":40, "X":10, "IX":9, "V":5, "IV":4, "I":1};
  console.log('num = ' + num);
  
  // this is a variable of type string
  str = "";

  // for loop to go over each item in roman
  for (var i in roman ) {
    console.log('i = ' + i);
    // calculates the Math Floor of the number passed in divided by the roman value
    // this will do the number passed divided by 1000 first
    // Example: convertToRoman(1201)
    // Math.floor(1201 / 1000) = 1
    var q = Math.floor(num / roman[i]); //Why?
    console.log('q = ' + q);
    // remove the value of q multiplied by roman[i]
    // Example: convertToRoman(1201)
    // q = 1
    // num = num - 1 * 1000;
    // this makes it so that num is less the roman symbol we just found
    num -= q * roman[i]; //Why?
    console.log('num = ' + num);
    // this is to make the roman number string
    // Example: num = 1201
    // i = 1000
    // q = 1
    // str = str + "M";
    // or
    // num = 3102
    // i = 1000
    // q = 3
    // str = str + "M" [repeated 3 times]
    // str = 'MMM' at the end of this
    str += i.repeat(q); //Why?
    console.log('str = ' + str);
  }

  // return the string
  return str;
}

console.log(convertToRoman(1201));

答案 1 :(得分:0)

var roman是一个关联数组,其中key是一个字符串,并且值为十进制系统值。

它按价值下降。

循环迭代数组计算索引的每个值包含在给定数字内的最大次数,并从数字中减去它,以便新迭代可以继续计算“休息”