Python将相等的值解释为不相等

时间:2014-06-01 15:58:34

标签: python

对于代码的这部分,它位于 for 循环

s = 'cl_num = %d, prev_cl_num = %d\n' % (cl_num, prev_cl_num);
fd.write( s );
if cl_num != prev_cl_num:
    bb.instructions[i].is_cache_miss = 1;
    s = 'instruction %x is cache miss, cl_num = %d, prev_cl_num = %d, base_cache_line = %d\n' % (bb.instructions[i].address, cl_num, prev_cl_num, base_cache_line);
    fd.write( s );
    bb.instructions[i].cache_line = cl_num - base_cache_line;
    prev_cl_num = cl_num;

我得到一个输出,就像在fd文件中一样,

cl_num = 65557, prev_cl_num = 65557
instruction 400558 is cache miss, cl_num = 65557, prev_cl_num = 65557, base_cache_line = 65557
cl_num = 65557, prev_cl_num = 65557
instruction 400560 is cache miss, cl_num = 65557, prev_cl_num = 65557, base_cache_line = 65557
cl_num = 65557, prev_cl_num = 65557
instruction 400568 is cache miss, cl_num = 65557, prev_cl_num = 65557, base_cache_line = 65557
cl_num = 65557, prev_cl_num = 65557
instruction 400570 is cache miss, cl_num = 65557, prev_cl_num = 65557, base_cache_line = 65557

您会看到,即使cl_num != prev_cl_num等于true,条件cl_num也会评估为prev_cl_num。为什么这样?

1 个答案:

答案 0 :(得分:3)

您有浮点值,但只将整数部分写入您的文件:

>>> '%d' % 3.3
'3'

注意.3小数部分是如何被忽略的; %d在内插值上调用int()

编写调试值时,请始终在格式化中使用repr()%r

s = 'cl_num = %r, prev_cl_num = %r\n' % (cl_num, prev_cl_num);
浮点值上的

repr()将它们格式化,就好像使用%17g格式化程序一样;显示17位小数,当指数为17或更高时使用科学记数法。