利用js生成一百以内的加减运算题 |
您所在的位置:网站首页 › vb设计100以内加减法 › 利用js生成一百以内的加减运算题 |
孩子五岁了,最近对算数题很感兴趣,于是写了一个小程序,自动生成一百以内的加减法运算题,可以打印出来,让孩子练习。 核心程序非常简单,就是利用js的随机数生成器,自动随机生成加减法运算题目和答案,答案和题目可以分开输出。 需求描述 生成一百以内的加减法运算题目 生成的题目和答案可以分开输出 可以指定生成的题目数量 可以指定生成的题目的最大值,默认为100 可以指定生成的题目的最小值,默认为0 可以指定生成的题目的运算符,默认为加减法 排除ab/ba这种重复的题目 核心源码123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657function generateMathProblems( num, max = 100, min = 0, operator = ["+", "-"]) { const problems = []; const answers = []; const set = new Set(); while (set.size < num) { // 生成随机数 let num1 = Math.floor(Math.random() * (max - min) + min); let num2 = Math.floor(Math.random() * (max - min) + min); if (num1 === 0 || num2 === 0) { continue; } let operatorStr = operator[Math.floor(Math.random() * operator.length)]; let answer = ""; if (operatorStr === "-") { if (num1 < num2) { [num1, num2] = [num2, num1]; } } const key = [num1, num2].sort((a, b) => b - a).join(operatorStr); if (set.has(key)) { continue; } // 计算答案 switch (operatorStr) { case "+": answer = num1 + num2; break; case "-": answer = num1 - num2; break; case "++": answer = num1 + num2 + min; break; case "--": answer = num1 - num2 - min; break; default: break; } // 生成题目和答案 const problem = `${num1} ${operatorStr} ${num2} = ___`; problems.push(problem); answers.push(answer); set.add(key); } console.log(set); return { problems: problems, answers: answers, };}generateMathProblems()函数接受4个参数,分别是题目数量、最大值、最小值、运算符。函数内通过循环生成指定数量的题目和答案,利用数组进行存储并返回。首先在指定范围内生成两个随机数,用来构造算式。在指定的运算符范围内,生成运算符字符串。根据运算符字符串计算出答案。最后将算式和答案存储在数组中,并返回存储题目和答案的对象。 打印实现排版打印,可以利用html2canvas和jspdf两个库,将html转换成canvas,然后再将canvas转换成pdf。 引入 html2canvas 和 jsPDF 库在 HTML 文件中引入 html2canvas 和 jsPDF 库: 12 编写转换函数使用 html2canvas 将 HTML 元素转换成 Canvas,再使用 jsPDF 将 Canvas 转换成 PDF。 12345678910111213141516171819function htmlToPdf(htmlElement, fileName) { // 设置页面大小和间距 const pdfWidth = htmlElement.offsetWidth; const pdfHeight = htmlElement.offsetHeight; const topMargin = 10; const bottomMargin = 10; // 将 HTML 元素转换成 Canvas html2canvas(htmlElement, { background: '#fff', scale: 2 // 倍数,提高清晰度 }).then(canvas => { const image = canvas.toDataURL('image/png'); const pdf = new jsPDF('p', 'pt', [pdfWidth, pdfHeight]); // 将 Canvas 转换成 PDF pdf.addImage(image, 'PNG', 0, topMargin, pdfWidth, pdfHeight); pdf.save(fileName + '.pdf'); });} 调用转换函数将需要转换的 HTML 元素传入转换函数,并指定保存的文件名: 123const element = document.querySelector('#pdf-content');const fileName = 'my-document';htmlToPdf(element, fileName);其中,element 是需要转换成 PDF 的 HTML 元素,fileName 是保存的文件名。在这个例子中,我将 HTML 元素的 id 设置为 pdf-content。 demo地址:https://www.mulianju.com/demos/gen-sums/ 本文永久链接: https://www.mulianju.com/gen-sums/ |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |