0

我最近有一项任务是根据用户给出的随机高度做一个空三角形。

它必须看起来像那样,但用户设置了高度

它必须看起来像那样,但用户是可以设置高度的人。
我的脚本现在看起来像这样:

var hgh = prompt("Set the triangle's height: ");

  document.write("<center><pre>");
  for (var i = 1; i <= hgh ; i++) {
    var s = "";
    for (var j = 1; j <= (2 * hgh - 1); j++) {
      if (i != hgh ) {
        if (j == hgh + 1 - i || j == hgh - 1 + i) {
           s += "X";
        }
        else {
          s += " ";
        }
      }
      else {
        s += "X";
      }
    }
    document.write(s);
    document.write("<br>");
  }
  document.write("</pre></center>");

结果如下所示:

我必须更正脚本的哪一部分才能正确显示三角形?

4

2 回答 2

1

问题是在这种情况下:

if (j == hgh + 1 - i ... )

hgh 实际上是一个字符串(因为 prompt 返回一个字符串)。因此,“+”运算符在这里处理字符串并将 hgh 和“1”连接起来,而不是添加这些值。如果输入“5”,(hgh + 1) 将得到“51”,而不是“6”。

快速解决方案:将表达式重写为 hgh - i + 1。没有字符串减法,因此 (hgh - i) 会将 hgh 转换为数字并进行适当的减法。

于 2021-04-13T14:13:20.907 回答
0

pre我采取了一种稍微不同的方法,但是当在元素中呈现而不是像上面那样直接写入页面时,它似乎可以正常工作。

const triangle=()=>{
  let pre=document.querySelector('pre');
  let height=Number( prompt('Set the triangle\'s height:') ) || false;
  let maxheight=32;

  // only proceed with valid integers above 1 & less than 33 in value...
  if( isNaN( height ) || height==false ){
    alert('Not a number numbnut!');
    return false;
  }
  if( height < 2 ){
    alert('Given height is too small');
    return false;
  }
  if( height > maxheight ){
    alert('Too high');
    return false;
  }

  // hwp: Half-Way Point
  let hwp;

  // k: for even numbered triangles subtract this value to the spaces
  let k=0;



  // calculate half way point
  if( height % 2 == 0 ){
    hwp=height/2;
    k=1;
  }else{
    hwp=( height - 1 ) / 2;
  }

  // characters used
  let c=String.fromCharCode(88);
  let s=String.fromCharCode(32);
  let n=String.fromCharCode(10);



  for( let i=0,j=0; i < height-1; i++,j++ ){
    let r=[];
    if( i == 0 ){
      /*
        top row should be a single X at the HWP
        preceeded by a certain number of spaces.
        Approx 2 spaces per char
      */
      r.push(s.repeat( hwp * 2 - k ));
      r.push(c);
    }else{
      /*
        subsequent rows have fewer spaces before the initial
        X but an increasing amount of spaces after.
      */
      r.push(s.repeat( ( hwp * 2 ) - j - k ) );
      r.push(c);
      r.push(s.repeat( ( j + i ) - 1 ) );
      r.push(c);
    }
    pre.innerHTML+=[ r.join(''), n ].join('');
  }
  // final row is only X chars ~ approx twice height value
  pre.innerHTML+=c.repeat( ( height * 2 ) - 1  );               
}

triangle();
pre{margin:1rem;}
<pre></pre>

于 2021-04-13T14:42:00.220 回答