使用前端在页面展示计算正方形的数量,如下:
实现代码
<html>
<head>
<meta charset="utf-8">
<title>正方形数量</title>
<style type="text/css">
</style>
</head>
<body>
行数:
<input id="input_row" type="text" placeholder="输入行数">
<br>
<br>
列数:
<input id="input_column" type="text" placeholder="输入列数">
<br>
<br>
<button onclick="generateMatrix()">
确定
</button>
<br>
<br>
<br>
<table id="matrix_table" cellspacing="0" cellpadding="10" bordercolor="blue" border="1"></table>
<br>
<br>
<br>
<div id="count_div"></div>
<script>
function generateMatrix() {
var input_row = document.getElementById("input_row");
var input_column = document.getElementById("input_column");
var matrix_table = document.getElementById("matrix_table");
var count_div = document.getElementById("count_div");
var k = 0;
var count = 0;
//清空表格和计数器
matrix_table.innerHTML = '';
count_div.innerHTML = '';
//循环行
for (var i = 0; i < input_row.value; i++) {
var row = document.createElement('tr');
//循环列
for (var j = 0; j < input_column.value; j++) {
k = (input_column.value - j) > (input_row.value - i) ? (input_row.value - i):(input_column.value - j);
count += parseInt(k);
var cell = document.createElement('td');
cell.textContent = k;
row.appendChild(cell);
}
matrix_table.appendChild(row);
}
//显示计数器
count_div.textContent = '图中正方形数量 = ' + count;
}
</script>
</body></html>