编写JavaScript以提示用户输入奇数。首先,检查用户是否输入了有效的奇数。然后,您需要在控制台上打印一个由与用户输入的数字相同数量的*字符组成的十字架。
到目前为止,我的代码是这样的
我已编辑了我的代码以包含正确的方式
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)
我可以在适当的时间内垂直播放,但我如何确保不重复*?
答案 0 :(得分:1)
最初你正在分配
let vertical = "*";
将其更改为
let vertical = "";
试试这个
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 += (" ")
}
console.log(vertical)
答案 1 :(得分:1)
你走在正确的轨道上。您需要在此处执行三个步骤。你需要像这样创建一个十字架(假设数字是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);
}