我需要在scheme中编写一个函数来计算平方数字的总和。
ex - (sum-of-digits 130) > 10这是我的功能。
(define (sum-of-digits x) (if (= x 0) 0 (+ (modulo x 10) (sum-of-digits (/ (- x (modulo x 10)) 10)))))它对某些数字不起作用。 当我输入(数字和130)时,它返回4.我该如何解决这个问题?
另外我需要用这个函数来找到0,1,4,16,20,37,42,58,89,145的停止数字
ex :- (stop? 42) #t (stop? 31) #f如何使用上面的和位函数和来做到这一点?
I need to write a function in scheme which calculates the sum of square digits.
ex - (sum-of-digits 130) > 10This is my function.
(define (sum-of-digits x) (if (= x 0) 0 (+ (modulo x 10) (sum-of-digits (/ (- x (modulo x 10)) 10)))))it doesn't work for some numbers. When I entered (sum-of-digits 130) , it returns 4. How can i fix this ?
Also I need to use this function to find the stop numbers which are 0,1,4,16,20,37,42,58,89,145
ex :- (stop? 42) #t (stop? 31) #fHow can I do this using the function sum of sum-of-digits above?
最满意答案
你忘了实际对每个数字进行平方 ,并且有一种更简单的方法来获得商:
(define (sum-of-digits x) (if (= x 0) 0 (+ (sqr (modulo x 10)) (sum-of-digits (quotient x 10)))))对于问题的第二部分:
(define (stop? x) (let ((sum (sum-of-digits x))) (if (member sum '(0 1 4 16 20 37 42 58 89 145)) #t #f)))You forgot to actually square each digit, and there's a simpler way to obtain the quotient:
(define (sum-of-digits x) (if (= x 0) 0 (+ (sqr (modulo x 10)) (sum-of-digits (quotient x 10)))))For the second part of the question:
(define (stop? x) (let ((sum (sum-of-digits x))) (if (member sum '(0 1 4 16 20 37 42 58 89 145)) #t #f)))更多推荐
发布评论