我已經在你的變量名改組,以使它更清楚一點。
// I'll use the example of 120 to demonstrate
// The total amount, e.g. 120
var amount = prompt("Enter amount ");
// First, convert the inputted string into an int
var amountAsInt = parseInt(amount, 10);
// Then, divide by 50 (which equals 2.4), and then use
// Math.floor() to "chop off" the decimal part
var numberOfFifties = Math.floor(amountAsInt/50);
// Leaving us with numberOfFifties = 2
// We can now use 'modulus' to give the amount left.
// If you haven't come across modulus before, it gives
// the remainder after dividing by the given number (here: 50)
var amountLeft = amount % 50;
// Do the same with the amount left to find the number of 20s
var numberOfTwenties = Math.floor(amountLeft/20);
if(numberOfFifties > 0){alert(numberOfFifties + " x " + "50 dollar bill(s)");}
if(numberOfTwenties > 0){alert(numberOfTwenties + " x " + "20 dollar bill(s)");}
的jsfiddle這裏: http://jsfiddle.net/7p57e3u1/3/
原因NaN的
你可以看到爲什麼你看這個的jsfiddle得到一個NaN的原因。
http://jsfiddle.net/pto52oe5/
要設置二十到等於整個字符串,因此它是「非數」(NAN)。
alert(twenty=parseInt(fifty/50) + " x " + "50 dollar bill");
在這裏,你似乎是假設
twenty=parseInt(fifty/50)
將作爲一個獨立的「零件」進行治療,但事實上,它使用的整個表達式,設置twenty
是整個字符串即在警報(輸出):
twenty = parseInt(fifty/50) + " x " + "50 dollar bill"
即(對於上面的例子)
twenty = "2 x 50 dollar bill"
一個有用的調試技術(以及創建更易於理解且可維護的代碼)是將事情分解成非常簡單的步驟,就像我在上面的示例代碼中所做的那樣。這(可以說)被分解得太過分了,但是用它作爲第一種技術來打破這樣的問題。
你'twenty'包含字符串'[數字] + 「X」 + 「50美元的鈔票」' – zvona
是的,但不應該parseInt函數轉換仍然是成多少?據我所知,當轉換字符串數字的一切權利的實際數字被忽略 –
@Jonon這就是'parseInt'做什麼。但是,當瀏覽器首先評估'twenty/20',並且假設你試圖將'string'除以20.它不會調用parseInt,它會使用Nubmer(二十)將它轉換爲數字,並且它變成'NaN '。 Ref:[Number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number)。 – fuyushimoya