为什么以下代码每次都会生成不同的输出(不是因为随机函数),但它为某些值(有时是其他值)提供了未定义的值.问题是什么?
function getRandom(ubound) {
return Math.floor((Math.random()*10) % ubound);
}
function getInterval() {
var interval = [getRandom(10), getRandom(10)];
if(interval[1] >= interval[0])
return interval;
else
getInterval();
}
function generateIntervals() {
for(var i = 0; i < n; i++)
intervals[i] = getInterval();
}
function printIntervals() {
for(var i = 0; i < n; i++)
console.log("Node " + (i + 1) + ": " + intervals[i]);
}
generateIntervals();
printIntervals();
Run Code Online (Sandbox Code Playgroud)
我得到的输出如下:
Node 1: 0,9
Node 2: 0,3
Node 3: undefined
Node 4: 2,2
Run Code Online (Sandbox Code Playgroud)
要么
Node …Run Code Online (Sandbox Code Playgroud) 我编写了一个非常简单的函数来为我提供两个边界之间所有整数的列表.
但是,它不是输出一个列表,而是给我一个由嵌套的mcons单元格构成的数据结构.
我究竟做错了什么?
#lang racket
(require rnrs/base-6)
(define (enumerate low high)
(if (> low high)
'()
(cons low
(enumerate (+ low 1) high))))
(enumerate 1 10)
;(mcons 1 (mcons 2 (mcons 3 (mcons 4 (mcons 5 (mcons 6 (mcons 7 (mcons 8 (mcons 9 (mcons 10))))))))))
Run Code Online (Sandbox Code Playgroud)