web js代码作业
作业题目
1.菱形代码
2.求所有三位水仙花数(水仙花数就是:个位的立方➕十位的立方➕百位的立方=这个数本身)
3.用循环求10!
4.用循环求10!+9!+8!……1!
5.假如一次只能走上一阶或者一下子蹦上两阶。 现在一共有N阶台阶,请你计算一下从第0阶到第N阶共有几种走法。
6.一对小兔子,4个月能长大,长大以后每个月生一对小兔子,求第n个月有多少对兔子。
代码
1.菱形代码
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
// *
// ***
// *****
// *******
// *****
// ***
// *
// 层 1 2 3 4
// 空 3 2 1 0
// 星 1 3 5 7
// star = current * 2 - 1
// up_layer = math.floor(total_layer / 2) + 1
// space = up_layer - current
layer = parseInt(prompt("请输入层数"))
up_layer = Math.ceil(layer / 2)
end_layer = Math.ceil(layer-up_layer)
for (let i = 1; i <= up_layer; i++){
str = ""
space_num = up_layer - i;
for(let j = 1;j <= space_num; j++){
str += " "
}
star_num = i * 2 -1
for(let j = 1; j <= star_num; j++){
str += "*"
}
console.log(str)
}
for (let b = end_layer; b > 0; b--){
str = ""
space_num = end_layer - b + 1;
for(let j=1; j<=space_num;j++)
{
str += " "
}
star_num = b * 2 - 1
for(let j = 1; j <= star_num; j++){
str += "*"
}
console.log(str)
}
</script>
</body>
</html>
2.求所有三位水仙花数(水仙花数就是:个位的立方➕十位的立方➕百位的立方=这个数本身)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script>
for (let i = 100; i <= 999; i++)
{
bai = parseInt(i / 100)
shi = parseInt(i % 100 /10)
ge = parseInt(i % 10)
sum = bai ** 3 + shi ** 3 + ge ** 3
if (sum == i)
{
console.log(i)
console.log(bai,shi,ge,sum)
}
// if (i == 109)
// {
// break
// }
}
</script>
</body>
</html>
3.用循环求10!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script>
function can(num){
let sum = num
for(let i = num - 1; i > 0; i--){
sum *= i
}
return sum
}
console.log(can(10))
</script>
</body>
</html>
4.用循环求10!+9!+8!……1!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script>
function can(num){
let sum = num
for(let i = num - 1; i > 0; i--){
sum *= i
}
return sum
}
let he = 0
for(let sum = 10; sum > 0; sum--){
he += can(sum)
// console.log(can(sum))
// console.log(he)
}
console.log(he)
</script>
</body>
</html>
5.假如一次只能走上一阶或者一下子蹦上两阶。 现在一共有N阶台阶,请你计算一下从第0阶到第N阶共有几种走法。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script>
function staircase(sum){
if(sum == 1 || sum == 2){
return sum
}
else if(sum > 2){
return staircase(sum - 1) + staircase(sum - 2)
}
else{
return -1
}
}
let sum
sum = window.prompt("请输入一共有多少阶台阶")
console.log(staircase(sum))
</script>
</body>
</html>
6.一对小兔子,4个月能长大,长大以后每个月生一对小兔子,求第n个月有多少对兔子。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script>
function rabbit(month){
let sum
if (month <= 4){
sum = 1
return sum
}
else{
sum = rabbit(month - 4) + rabbit(month - 1)
return sum
}
}
let month
month = window.prompt("请输入有多少个月")
console.log(rabbit(month))
</script>
</body>
</html>