我想尝试使等腰三角形成为一个三角形,但是到目前为止,我遇到了麻烦:
function pyramid(N) {
let result = "";
for (let i = 1; i <= N; i++) {
for (let j = 1; j <= N; j++) {
if (i >= j) {
result += i + " ";
} else {
result += " ";
}
}
result += '\n';
}
return result
}
console.log(pyramid(5));
我的输出:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
我想要的输出是:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
是否需要再次循环以使其成功?
下面的代码将为您提供所需的输出。
function pyramid(N){
let result = "";
for(let i = 1 ; i <= N ; i++) {
for(j = N ; j > i ; j--) {
result += " ";
}
for(j = 1 ; j<= i ; j++) {
result += i + " ";
}
result += "\n";
}
return result;
}
console.log(pyramid(5));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句