Write the JavaScript to prompt the user to enter an odd number. First, check that the user has entered a valid odd number. Then you need to print to the console a cross made of the same number of * characters as the number the user entered.
到目前为止我已经有了我的代码
我已经编辑了我的代码以包含正确的方法
let num = prompt("Enter an odd number");
let star = "*";
let vertical = "";
let horizontal = star.repeat(num);
while (num%2 == 0) {
console.log("User did not enter an odd number");
num = prompt("Enter an odd number");
}
console.log("User's number is " +num);
let pos = +(Math.ceil(num/2));
// I need to divide the input number by 2 and round up
for (var h = 0; h < pos; h++){
vertical += (" ")
}
for (var v = 0; v < pos; v++){
vertical += vertical + "\n *"
}
vertical += "*"
console.log (vertical)
我可以垂直\n适当的次数,但是我如何确保我不会过度重复*?
最佳答案
你走在正确的道路上。您需要在此处执行三个步骤。您需要创建一个像这样的十字架(假设数字是 13):
*
*
*
*******
*
*
*
您需要创建 Math.floor(13/4)
(共 3)行单颗星,每个星位于 Math.floor(13/4)
空格。然后,您需要从位置 0 开始的一行 Math.ceil(13/2)
星星。最后,您需要与该行之前相同数量的星星,因此您可以执行相同的操作又来了。
使用你的代码,我会做这样的事情:
let num = prompt("Enter an odd number");
while (num%2 == 0) {
console.log("User did not enter an odd number");
num = prompt("Enter an odd number");
}
console.log("User's number is " +num);
let star = " ";
let pos = Math.floor(num/4);
let vertical = star.repeat(pos) + "*";
for (var i = 0; i < pos; i++) {
console.log(vertical);
}
console.log("*".repeat(Math.ceil(num/2)));
for (var i = 0; i < pos; i++) {
console.log(vertical);
}
关于javascript - for循环中在字符串前面添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46627200/