换句话说,这样做
index = &array[x] - &array[0];
Run Code Online (Sandbox Code Playgroud)
是否始终保证(根据C标准)&array [0] <=&array [x],还是依赖于编译器?与此主题相关的C标准章节是什么?
所以,我正在学习C,我目前正在学习计算机系统:程序员观点第3版和相关实验室.我现在正在做第一个实验室,我必须实现(并因此实现)以下功能.
/*
* fitsBits - return 1 if x can be represented as an
* n-bit, two's complement integer.
* 1 <= n <= 32
* Examples: fitsBits(5,3) = 0, fitsBits(-4,3) = 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 15
* Rating: 2
*/
int fitsBits(int x, int n) {
int sign_bit = (x >> 31 & 1);
int minus_one = ~1+1;
int n_minus_one = n + minus_one;
return (!(x >> n_minus_one) …Run Code Online (Sandbox Code Playgroud) 所以,我正在努力通过 SICP。第 4 章的第一个练习是:
练习 4.1。请注意,我们无法判断元循环求值器是从左到右还是从右到左计算操作数。它的求值顺序是从底层 Lisp 继承而来的:如果值列表中 cons 的参数是从左到右求值的,那么值列表将从左到右求值;如果 cons 的参数是从右到左计算的,那么值列表将从右到左计算操作数。编写一个从左到右计算操作数的值列表版本,而不管底层 Lisp 中的计算顺序如何。还要编写一个从右到左计算操作数的值列表版本。
原来的功能是
(define (list-of-values exps env)
(if (no-operands? exps)
'()
(cons (eval (first-operand exps) env)
(list-of-values (rest-operands exps) env))))
Run Code Online (Sandbox Code Playgroud)
我的解决方案如下:
;;; left-to-right
(define (list-of-values-l2r exps env)
(if (no-operands? exps)
'()
(let ((first-exp (eval (first-operand exps) env)))
(cons first-exp
(list-of-values-l2r (rest-operands exps) env)))))
;;; right-to-left
(define (list-of-values-r2l exps env)
(list-of-values-l2r (reverse exps) env))
Run Code Online (Sandbox Code Playgroud)
但是,我不确定我所做的是否正确。我的直觉是 let 语句强制执行 eval,有人可以确认吗?
我刚刚开始学习C.我试图通过计算找到一个int的最大值(实际上我试图通过相同的方法找到一个浮点数的最大值,但我想在int上测试它第一).逻辑似乎没问题,但我的函数总是在结尾返回0.
int max_int_helper(int base)
{
int prev_i, next_i, counter;
counter = 1;
prev_i = next_i = base + counter;
// found max
if (next_i < base) {
printf("WE RETURN BASE %d\n", base);
return base;
} else {
while(prev_i <= next_i)
{
prev_i = next_i;
counter *= 2;
next_i = base + counter;
}
max_int_helper(prev_i);
}
}
Run Code Online (Sandbox Code Playgroud)
我在我的主要功能中这样称呼它
printf("max int calculated: %d", max_int_helper(0));
Run Code Online (Sandbox Code Playgroud)
但是当我运行这个东西时,我得到了这个:
WE RETURN BASE 2147483647 max int calculated:0
我明确地把printf语句,所以我"确定"我只返回一次,值是正确的.
请指出我哪里出错了.