我正在编写一个代码,无需使用库方法即可将十进制数转换为二进制数。但是使用while循环。它似乎陷入了无限循环。
在调试器模式下,我试图查看x
. 但即使当 的值为x
0 或 1 时,while 循环也不会退出。它是八度音程中的错误还是 Matlab 有这个问题(我没有 Matlab 或无法使用它)?
function ans = dec2bin(input)
x = int16(input);
y = [];
while (x!=1) || (x!=0)
y=[mod(x,int16(2)) y];
x=idivide(x,int16(2));
end
y=[mod(x,int16(2)) y];
ans = arrayfun(@(a) mat2str(a) ,y);
end
条件(x!=1) || (x!=0)
将始终为真 - 如果 x 为 1,则不等于 0,反之亦然。您应该使用&&
逻辑条件,而不是||
:
while (x!=1) && (x!=0)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句