我是JavaScript的初学者,我的代码遇到了麻烦。当它不输出答案时,我似乎无法弄清楚代码出了什么问题。我正在尝试将用户输入的罗马数字转换为其相应的印度阿拉伯数字。到目前为止,这是我的代码。
<!doctype html>
<html>
<body>
<h2>JavaScript Roman to Decimal Converter(1-10)</h2>
<p id="demo"></p>
<input id="roman" value=""/>
<button onclick="myFunction()">Convert</button>
</form>
<script>
function myFunction(){
var sum=0;
var len=romanNum.length();
var i;
var previous=10;
for (i=0; i<len; i++)
{
switch (romanNum.charAt(i))
{
case 'X':
sum=sum+10;
if(previous<10)
sum=sum-2*previous;
previous=10;
break;
case 'V':
sum=sum+5;
if(previous<5)
sum=sum-2*previous;
previous=5;
break;
case 'I':
sum=sum+1;
previous=1;
}
}
decimalNum=sum;
return decimalNum;
document.getElementById("demo").innerHTML=decimalNum+" is the answer.";
</script>
</body>
</html>
答案 0 :(得分:2)
here中最简单的解决方案,而不是复杂的switch语句。
var decimal = [1000, 500, 100, 50, 10, 5, 1];
var roman = ["M", "D", "C", "L", "X", "V", "I"];
function myFunction() {
var str = document.getElementById("roman").value;
var result = 0;
var decimal = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
var roman = ["M", "CM","D","CD","C", "XC", "L", "XL", "X","IX","V","IV","I"];
for (var i = 0;i<=decimal.length;i++) {
while (str.indexOf(roman[i]) === 0){ //checking for the first characters in the string
result += decimal[i]; //adding the decimal value to our result counter
str = str.replace(roman[i],''); //remove the matched Roman letter from the beginning
}
}
document.getElementById("demo").innerHTML = "<p style='color: green;'>The equivalent decimal for Roman Numeral " + str + " is " + result + "</p>";
}
<!doctype html>
<html>
<body>
<h2>JavaScript Roman to Decimal Converter(1-1000)</h2>
<p id="demo"></p>
<input id="roman" value=""/>
<button onclick="myFunction()">Convert</button>
</body>
</html>
答案 1 :(得分:1)
在这里我创建了一个简短的演示,请检查我留下的评论https://jsbin.com/luceleqepe/edit?html,output
<!doctype html>
<html>
<body>
<h2>JavaScript Roman to Decimal Converter(1-10)</h2>
<p id="demo"></p>
<input id="roman" value=""/>
<button onclick="myFunction()">Convert</button>
</form>
<script>
function myFunction(){
var sum=0;
// you forgot to get romanNum value
var romanNum = document.getElementById("roman").value;
// String.length is an property not a method
var len=romanNum.length;
var i;
var previous=10;
for (i=0; i<len; i++)
{
switch (romanNum.charAt(i))
{
case 'X':
sum=sum+10;
if(previous<10)
sum=sum-2*previous;
previous=10;
break;
case 'V':
sum=sum+5;
if(previous<5)
sum=sum-2*previous;
previous=5;
break;
case 'I':
sum=sum+1;
previous=1;
}
}
decimalNum=sum;
// no one experession will be executed, if it placed after return
document.getElementById("demo").innerHTML=decimalNum+" is the answer.";
return decimalNum;
// also, you forgot to close the function
}
</script>
</body>
</html>