我正在完成我的信息学作业,我为我的问题写了这些:
创建一个值为 154 的变量 s 和一个值为 6 的变量 p。在屏幕上以十进制和二进制形式显示其值。
s=154
p=6
bs=bin(s)
bp=bin(p)
print("In decimal form, s =",s,"and p =",p)
print("In binary form, s =",bs[2:],"and p =",bp[2:])
将变量s和p进行按位或运算,并将结果写入变量s。将十进制和二进制形式的值输出到屏幕。
s=s|p
bsp=bin(s)
print("In decimal form, the value is",s)
print("In binary form, the value is",bsp[2:])
对变量s和p进行按位右移2位操作,并将结果记录在相应的变量中。在屏幕上以十进制和二进制形式显示值。
#print(s)
sbutshift2digit=s>>2
binsshift=bin(sbutshift2digit)
pbutshift2digit=p>>2
binpshift=bin(pbutshift2digit)
print("for the operation of bitwise shift to the right by 2 bits on the variables s, the value in decimal is",sbutshift2digit)
print("for the operation of bitwise shift to the right by 2 bits on the variables s, the value in binary is",binsshift[2:])
print("\n")
print("for the operation of bitwise shift to the right by 2 bits on the variables s, the value in decimal is",pbutshift2digit)
print("for the operation of bitwise shift to the right by 2 bits on the variables s, the value in binary is",binpshift[2:])
这是我的第三部分代码的结果:
for the operation of bitwise shift to the right by 2 bits on the variables s, the value in decimal is 39
for the operation of bitwise shift to the right by 2 bits on the variables s, the value in binary is 100111
for the operation of bitwise shift to the right by 2 bits on the variables s, the value in decimal is 1
for the operation of bitwise shift to the right by 2 bits on the variables s, the value in binary is 1
问题是,对于变量s按位右移2位的操作,十进制的值应该是38,而不是39。 我真的不知道出了什么问题......
你正在覆盖你的变量。执行按位
OR
后,变量 s
现在为 158,而不是 154。然后,您将对这个新值而不是原始值执行位移。要修复它,您只需在操作之间重置 s
和 p
:
s = 154
p = 6
bs = bin(s)
bp = bin(p)
print("In decimal form, s =", s, "and p =", p)
print("In binary form, s =", bs[2:], "and p =", bp[2:])
# Perform a bitwise OR operation on the variables s and p
s = s | p
bsp = bin(s)
print("In decimal form, the value is", s)
print("In binary form, the value is", bsp[2:])
# Reset your variables
s = 154
p = 6
bs = bin(s)
bp = bin(p)
# Perform the operation of bitwise shift to the right by 2 bits on the variables s and p
sbutshift2digit = s >> 2
binsshift = bin(sbutshift2digit)
pbutshift2digit = p >> 2
binpshift = bin(pbutshift2digit)
print("For the operation of bitwise shift to the right by 2 bits on the variable s, the value in decimal is", sbutshift2digit)
print("For the operation of bitwise shift to the right by 2 bits on the variable s, the value in binary is", binsshift[2:])
print("\n")
print("For the operation of bitwise shift to the right by 2 bits on the variable p, the value in decimal is", pbutshift2digit)
print("For the operation of bitwise shift to the right by 2 bits on the variable p, the value in binary is", binpshift[2:])