Codehs Inventory:我在这段代码中做错了什么?

问题描述

在这代码上工作了很长时间,但仍然无法弄清楚这里出了什么问题......当我点击检查代码时,它说:

  1. 如果我尝试移除 25 件物品,库存中应该还剩下 20 件物品
  2. 如果我删除了 20 个项目,你应该说“All Out!”

但我的代码在这两种情况下都有效。所以这是我的代码

var STARTING_ITEMS_IN_INVENTORY = 20;



   function start(){

    var numItems = STARTING_ITEMS_IN_INVENTORY; 
    
    
    while(numItems>0 ){
        
    println("We have "+numItems+" items in inventory");
    
    
    var number=readInt("How many would you like to buy?");
    numItems-=number;
    
    if(numItems>0){
    println("Now we have "+numItems+" left");
    println("");
    }
    
    if(numItems==0){
        println("");
        println("All Out!");
    }else if(numItems<0){
        
        println("There is not enough in inventory for that purchase");
       
    }
    
    }
}

请帮我解决这个问题

解决方法

您标记了您的帖子 javascript,但您的代码没有。 我敢打赌这是你明天的作业...

我重写了你的代码以满足 js 的需求:

var STARTING_ITEMS_IN_INVENTORY = 20;

function start() {
  
    var numItems = STARTING_ITEMS_IN_INVENTORY;
  
    while (numItems > 0) {
        alert("We have " + numItems + " items in inventory");
        var number = prompt("How many would you like to buy?");
        numItems -= number;

        if (numItems > 0) {
            alert("Now we have " + numItems + " left");
        } else if (numItems == 0) {
            alert("All Out!");
        } else if (numItems < 0) {
            alert("There is not enough in inventory for that purchase");
        }
    }
}

start();

我给你下面的代码,这就是你想要的,我建议你修改它以了解算法和js是如何工作的。

var STARTING_ITEMS_IN_INVENTORY = 20;

function start() {

    var numItems = STARTING_ITEMS_IN_INVENTORY;

    while (numItems > 0) {
        var number = prompt("How many would you like to buy? (" + numItems + " left)");
        
        if (numItems - number > 0) {
            numItems -= number;
        } else if (numItems - number == 0) {
            numItems -= number;
        } else if (numItems - number < 0) {
            alert("There is not enough in inventory for that purchase,please retry");
        }
    }
    alert("All Out!");
}

start();

建议和信息:

  • readLn()printLn() 不是 javascript 中的核心函数
  • 在网络开发中,您不应为此目的使用 prompt()alert()
  • 在将库存分配给 numItems 之前检查库存的未来项目计数
  • 阅读https://www.w3schools.com/js/DEFAULT.asp
,

我发现这是满足自动检查器的最简单方法。

var STARTING_ITEMS_IN_INVENTORY = 20;

function start() {

    var numItems = STARTING_ITEMS_IN_INVENTORY;

    while(numItems > 0){
        println("We have " + numItems + " items in inventory.");
        var howMany = readInt("How many items would you like to buy? ");
        if(howMany > numItems){
            println("There is not enough in inventory for that purchase.");
            println("");
        } else {
            numItems -= howMany;
            println("Now we have " + numItems + " left.");
            println("");
        }
    }
    println("All Out!");
}