我使用 Octave 编写了这段代码。
x=0.0;
while (x~=1.0)
x=x+0.1;
fprintf('x=%20.18f\n',x)
pause
endwhile
我想在 x
等于 1
时停止代码。
所以,我放了一些这样的代码
x=0.0;
while (x~=1.0)
x=x+0.1;
fprintf('x=%20.18f\n',x)
if abs(x-1)<(eps/2),
print(x)
endif
pause
endwhile
但是没有用,无限显示数字。当 x
等于 1
时,如何编写代码来停止此代码?
最佳答案
添加时:
x = 0.0;
x = x + 0.1;
你可以得到 x = 0.100000000000000006
例如由于数值精度所以 while
永远不会退出,因为它总是不同于 1
.
您可以使用小于 <
的值运算符在 x
时停止循环等于1
:
x=0.0;
while (x < 1.0)
x=x+0.1;
fprintf('x=%20.18f\n',x)
if abs(x-1)<(eps/2),
print(x)
endif
pause
endwhile
关于octave - 我想在 x 等于 1 时停止代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66468726/