js矩形,数组,杨辉三角

矩形:

let readline = require("readline-sync");
console.log("请输入矩阵的宽");
let width = readline.question();
let i,j,k = 1,sum = 0;
let arr = [];
for(i=0;i<width;i++)
{
arr[1] = [];
}
for(i=0;i<width;i++)
{
for(j=0;j<width;j++)
{
arr[i][j] = k;
k++;
}
}
for(i=0;i<width;i++)
{
for(j=0;j<width;j++)
{
if(i==j)
{
sum = sum +arr[i][j];
}
}
console.log(arr[i]);
}
console.log(sum);
数组:
let readline = require("readline-sunc");
console.log("请选择您要执行的操作: 1.求最大值 2.求最小值 3.求和 4.求平均数");
let choose = parseInt(readline.quextion(""));
let arr = [3,5,8,1,12,7,8,6,1,5,7,9,11,15,12,17,1,8,6,5,"a"];
switch (choose){
case 1:
{
let max = 0;
for (let i = 0; 1 <=arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
console.log("最大值为:",max);
break;
}
case 2:
{
let min = arr[0];
for (let i = 0; i <= arr.length;i++) {
if (arr[i] < min){
min = arr[i];
}
}
console.log("最小值为:",min);
break;
}
case 3:
{
let sum = 0;
for (let i = 0; i < arr.length; i++){
sum += arr[i];
}
console.log("数组和为:",sum);
break;
}
case 4:
{
let sum = 0;
for (let i = 0; i< arr.length; i++){
sum += arr[i];
}
let avg = sum / arr.length;
console.log("数组的平均数为",avg);
break;
}
}
杨辉三角:
let readline = require("readline-sync");
console.log("请输入杨辉三角的行数:");
let line = readline.question();
let arr = [];
let str = ""
for (let i = 0; i < line; i++) {
arr[i] = [];
for (let j = 0; j <= i; j++){
if (j == 0 ||i == j)
{
arr[i][j] = 1;
}
else{
arr[i][j] = arr[i-1][j-1]+arr[i-1][j];
}
}
for (let j = 0; j<line - 1;j++) {
str +=" ";
}
console.log(str + arr[i]);
str = "";
}
posted on 2019-08-23 15:49  dazhongma233  阅读(173)  评论(0编辑  收藏  举报