英文:
Pattern of Y using a "O" string
问题
这是我用于“Y”图案的JavaScript代码,但底部不在中心,我的代码有什么问题?将接受奇数。
我期望得到这个输出:
O O
O O
O
O
O
注意:代码部分已被省略,只提供了代码的翻译和预期输出。
英文:
This is my javascript code for the Y
pattern but in the bottom part, it is not in the center what's wrong with my code? will accept odd numbers
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const char = "Y";
const size = 5; //all odd numbers
let output = ""
if (char === 'Y') {
for (let i = 0; i < size; i++) {
for (let j = 0; j < size; j++) {
if (i === j && i < size / 2 || j === size / 2 && i >= size / 2 || i + j === size - 1 && i < size / 2 || (j === 0 && i >= size / 2))
{
output += 'O';
} else {
output += ' ';
}
}
output += '\n';
}
}
console.log(output);
<!-- end snippet -->
I expect to have this output:
O O
O O
O
O
O
答案1
得分: 1
Changing j === 0
to j === 2
will solve this problem. For work universally, just use j === (size - 1) / 2
const char = "Y";
const size = 5;
let output = "";
if (char === 'Y') {
for (let i = 0; i < size; i++) {
for (let j = 0; j < size; j++) {
if (i === j && i < size / 2 || j === size / 2 && i >= size / 2 || i + j === size - 1 && i < size / 2 || (j === (size - 1) / 2 && i >= size / 2)) {
output += 'O';
} else {
output += ' ';
}
}
output += '\n';
}
}
console.log(output);
英文:
Changing j === 0
to j === 2
will solve this problem. For work universally, just use j === (size - 1) / 2
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const char = "Y";
const size = 5;
let output = ""
if (char === 'Y') {
for (let i = 0; i < size; i++) {
for (let j = 0; j < size; j++) {
if (i === j && i < size / 2 || j === size / 2 && i >= size / 2 || i + j === size - 1 && i < size / 2 || (j === (size - 1) / 2 && i >= size / 2))
{
output += 'O';
} else {
output += ' ';
}
}
output += '\n';
}
}
console.log(output);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论