如何使用嵌套循环生成10个和不为69或42的x+y数学题?
代码改进建议
先明确你当前代码存在的几个问题:
total变量未初始化就参与判断,会导致逻辑错误- 外层
while条件写反了,应该是当total === 69 || total === 42时继续生成新的x和y,而非不等于时循环 - x的判断条件写错了,把42写成了4,导致x可能取到42
- 没有计算
total = x + y,循环条件完全失效
以下是用嵌套循环实现需求的优化版本,逻辑更清晰:
// 外层循环:生成10道题 for (var i = 0; i < 10; i++) { var x, y, total; // 内层循环:生成符合条件的x和y,直到和不等于69或42 do { x = Math.floor(Math.random() * 100); y = Math.floor(Math.random() * 100); total = x + y; } while (total === 69 || total === 42); console.log(x + "+" + y); }
如果需要额外限制x和y本身也不能是69或42(从你原代码逻辑看有这个意图),可以调整内层循环的判断条件:
for (var i = 0; i < 10; i++) { var x, y, total; do { x = Math.floor(Math.random() * 100); y = Math.floor(Math.random() * 100); total = x + y; // 同时限制x、y本身不是69/42,且和也不是69/42 } while (x === 69 || x === 42 || y === 69 || y === 42 || total === 69 || total === 42); console.log(x + "+" + y); }
这个版本用do-while作为内层嵌套循环,确保每次生成的题目都符合要求,代码结构简洁易读,完全满足你用嵌套循环实现需求的要求。
内容的提问来源于stack exchange,提问作者CorgisAreBest
相关产品推荐
相关产品推荐

