基于Javascript中给定高度的空心三角形

问题描述

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

It had to look like that but the user set the height

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

Int

结果如下:

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

解决方法

问题出在这种情况下:

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

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

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

,

我采用了稍微不同的方法,但在 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>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...