不能为菱形图案制作底部金字塔

我今天刚开始使用 javascript 来完成一项学校任务。我的任务是用星星制作菱形图案,但我不明白如何制作底部金字塔


我试过改变一切,这段代码在我脑海中起作用但没有正确执行。这是我制作的代码


function clicked() {

  var x = document.getElementById("num").value;

  if (x < 50) {

    document.write("Your Number is: " + x + "<br />Your number is lower than 50<br />");

  } else if (x > 50) {

    document.write("Your Number is: " + x + "<br />Your number is more than50<br />");

  } else {

    document.write("Your Number is: " + x + "<br />Your number is equal to 50<br />");

  }

  for (var i = 1; i <= x; i++) {

    for (var k = 1; k <= x - i; k++) {

      document.write("&nbsp;");

    }

    for (var j = 1; j <= i; j++) {

      document.write("*");

    }

    document.write("<br/>");

  }

  var m = 1;

  for (var l = x - m; l <= x - m; m++) {

    for (var n = 1; n <= l; n++) {

      document.write("*");

    }

    document.write("<br/>");

  }

}

<body>

<input type="number" id="num" placeholder="Enter Number">

<br>

<button onclick="clicked()">SUBMIT</button>

</body>


DIEA
浏览 93回答 1
1回答

神不在的星期二

我对您的代码进行了细微修改。你几乎拥有它。我会按原样重用相同的嵌套 for 循环。只需更改循环的顶层。金字塔的顶端运行:&nbsp; &nbsp; for(var i=1; i<=x;i++)底部金字塔用于:&nbsp; &nbsp; for(var i=x-1; i>=1; i--)您应该考虑将重复的嵌套代码移动到一个函数中,并将 的值i作为参数传递给该函数。function clicked() {&nbsp; var x = document.getElementById("num").value;&nbsp; if (x < 50) {&nbsp; &nbsp; document.write("Your Number is: " + x + "<br />Your number is lower than 50<br />");&nbsp; } else if (x > 50) {&nbsp; &nbsp; document.write("Your Number is: " + x + "<br />Your number is more than50<br />");&nbsp; } else {&nbsp; &nbsp; document.write("Your Number is: " + x + "<br />Your number is equal to 50<br />");&nbsp; }&nbsp; for (var i = 1; i <= x; i++) {&nbsp; &nbsp; for (var k = 1; k <= x - i; k++) {&nbsp; &nbsp; &nbsp; document.write("&nbsp;");&nbsp; &nbsp; }&nbsp; &nbsp; for (var j = 1; j <= i; j++) {&nbsp; &nbsp; &nbsp; document.write("*");&nbsp; &nbsp; }&nbsp; &nbsp; document.write("<br/>");&nbsp; }&nbsp; for (var i = x - 1; i >= 1; i--) {&nbsp; &nbsp; for (var k = 1; k <= x - i; k++) {&nbsp; &nbsp; &nbsp; document.write("&nbsp;");&nbsp; &nbsp; }&nbsp; &nbsp; for (var j = 1; j <= i; j++) {&nbsp; &nbsp; &nbsp; document.write("*");&nbsp; &nbsp; }&nbsp; &nbsp; document.write("<br/>");&nbsp; }}<body><input type="number" id="num" placeholder="Enter Number"><br><button onclick="clicked()">SUBMIT</button></body>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript