while循环没有给出正确的结果

时间:2015-07-18 02:26:35

标签: javascript

我是JS的新手。 现在我正在尝试编写一个脚本,当我购买手机时,价格会从我的信用卡价格中扣除。 这是代码

    // Total Money in my Credit Card
var totalMoneyForCredit=150;

// Your Current Billing from Shop
var moneySpent=0;

// Prices of Phones
var samsungPrice=33;
var sonyPrice=22;
var nokiaPrice=22;

// Asseorices for mobile

var charger=5;
var headset=10;


// Ask user for Purchasing Which mobies


while(totalMoneyForCredit>0){
    var order=prompt("Please enter the mobile you want to Purchase");
    if (order==='sam') {
        moneySpent=moneySpent+samsungPrice;

        totalMoneyForCredit=totalMoneyForCredit-moneySpent;

    }
    else if (order==='nokia') {
        moneySpent=moneySpent+nokiaPrice;
        totalMoneyForCredit=totalMoneyForCredit-moneySpent;


    }

    else if (order==='sony') {
        moneySpent=moneySpent+sonyPrice;

        totalMoneyForCredit=totalMoneyForCredit-moneySpent;

    }
    document.write(  '<b>' +  ' You spent ' + moneySpent  + " and the money left in your credit is " + totalMoneyForCredit + '</br>');

}

它工作正常,但是当我第四次购买诺基亚或任何手机时,价格显示不正确。

Snapshot

我为什么花了150分中的88分仍然剩下的钱是-70。 请告诉我我在哪里做错了。 感谢。

2 个答案:

答案 0 :(得分:0)

您在以前的交易中剩余的18个中有88个。所以你剩下18-88 = -70。

答案 1 :(得分:0)

我会这样做,从总金额中扣除手机价格,而不是剩余金额中的总金额。

    // Total Money in my Credit Card
var totalMoneyForCredit=150;

// Your Current Billing from Shop
var moneySpent=0;

// Prices of Phones
var samsungPrice=33;
var sonyPrice=22;
var nokiaPrice=22;

// Asseorices for mobile

var charger=5;
var headset=10;


// Ask user for Purchasing Which mobies


while(totalMoneyForCredit>0){
    var order=prompt("Please enter the mobile you want to Purchase");
    if (order==='sam') {
        moneySpent=moneySpent+samsungPrice;

        totalMoneyForCredit=totalMoneyForCredit-samsungPrice;

    }
    else if (order==='nokia') {
        moneySpent=moneySpent+nokiaPrice;
        totalMoneyForCredit=totalMoneyForCredit-nokiaPrice;


    }

    else if (order==='sony') {
        moneySpent=moneySpent+sonyPrice;

        totalMoneyForCredit=totalMoneyForCredit-sonyPrice;

    }
    console.log(' You spent ' + moneySpent  + " and the money left in your credit is " + totalMoneyForCredit);

}
alert('You ran out of money!');

相关问题