[问题] Roman Numeral Converter

楼主: pplle (鱼)   2017-05-24 00:00:56
之前在练习freeCodeCamp上的题目遇到问题,想请问大家。
po错版麻烦请告知。
freeCodeCamp的题目是数字转罗马字。
我的程式如下:
var symbolCount = 0;
var rNum = 0;
var romanNStr = ""; //组出的罗马数字
function convertToRoman(num) {
rNum= num;
//先算开头M的个数
symbolCount = Math.floor(rNum/1000);
rNum = rNum -(1000*symbolCount);
for(var i = 0; i < symbolCount; i++ ){
romanNStr+="M";
}
calSymbol("M", "D", "C", 100);
calSymbol("C", "L", "X", 10);
calSymbol("X", "V", "I", 1);
return romanNStr;
}
//以三个为一组计算
function calSymbol(b, m, s, val){
symbolCount = Math.floor(rNum / val);
if(symbolCount == 9){
romanNStr += s + b;
rNum -= (9*val);
symbolCount = 0;
}
if(symbolCount == 4){
romanNStr += s + m;
rNum -= (4*val);
symbolCount = 0;
}
if(symbolCount >= 5){
romanNStr += m;
rNum -= (5 * val);
symbolCount -= 5;
}
for(var i = 0; i < symbolCount ; i++){
romanNStr += s;
rNum -= (1 * val);
}
}
================================
我知道我的程式不是最佳解,
但执行freeCodeCamp提供的[Run tests]按钮,仅有converToRoman(2)过关。
我自己也找不到问题,
麻烦高手跟我说我的程式哪里有问题,谢谢
freeCodeCamp的test如下
convertToRoman(2) should return "II".
convertToRoman(3) should return "III".
convertToRoman(4) should return "IV".
convertToRoman(5) should return "V".
convertToRoman(9) should return "IX".
convertToRoman(12) should return "XII".
convertToRoman(16) should return "XVI".
convertToRoman(29) should return "XXIX".
convertToRoman(44) should return "XLIV".
convertToRoman(45) should return "XLV"
convertToRoman(68) should return "LXVIII"
convertToRoman(83) should return "LXXXIII"
convertToRoman(97) should return "XCVII"
convertToRoman(99) should return "XCIX"
convertToRoman(500) should return "D"
convertToRoman(501) should return "DI"
convertToRoman(649) should return "DCXLIX"
convertToRoman(798) should return "DCCXCVIII"
convertToRoman(891) should return "DCCCXCI"
convertToRoman(1000) should return "M"
convertToRoman(1004) should return "MIV"
convertToRoman(1006) should return "MVI"
convertToRoman(1023) should return "MXXIII"
convertToRoman(2014) should return "MMXIV"
convertToRoman(3999) should return "MMMCMXCIX"
作者: EPGo   2017-05-24 10:08:00
https://jsfiddle.net/n3xa17ox/ 这样子看的出来问题在哪~
楼主: pplle (鱼)   2017-05-24 20:49:00
很抱歉,还是看不出来…程式码我看过N次了Orz...
作者: EPGo   2017-05-24 21:59:00
检查console发现呼叫多次会因为 romanNStr 没有清空导致return出来的答案错误 EX: convertToRoman(2) = II再 convertToRoman(3) 却变成 IIIII我直觉想法是再多一个变量来储存输出的值,求出答案将答案给该变量,并且清空 romanNStr 以便下次计算https://jsfiddle.net/n3xa17ox/2/ 可以参考看看 : )
楼主: pplle (鱼)   2017-05-25 16:53:00
太感谢E大了,有恍然大悟的感觉,晚上就来改我的程式,谢谢

Links booklink

Contact Us: admin [ a t ] ucptt.com