问题描述
它必须看起来像那样,但用户是可以设置高度的人。
我的脚本现在看起来像这样:
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>