我试图制作一个javascript程序,将20到100之间的数字换成单词。所以我写了这个 -
var num = prompt("enter a number");
if (num>20 && num<100)
{
words(num);
}
else alert("Please enter a number between 20 and 100");
function words(num)
{
var ones = ["","one","two","three","four","five","six", "seven","eight", "nine"];
var tens = ["", "", "twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninety"];
var div= num/10;
var rem= num%10;
if (rem==0)
document.write(num+" = "+tens[div]);
else
document.write(num+" = "+tens[div]+" "+ones[rem]);
}
问题是如果我输入30,40这样的数字可以被10整除我得到正确的输出但如果我输入32它将显示“32 =未定义的两个”。 我做错了什么? 我是JS的新手,所以不太了解。
答案 0 :(得分:2)
32/10
为3.2
,而不是3
。你必须对结果进行舍入。
更改
var div= num/10;
到
var div= Math.floor(num/10);
答案 1 :(得分:1)