gpt4 book ai didi

octave - 我想在 x 等于 1 时停止代码

转载 作者:行者123 更新时间:2023-12-04 02:27:31 24 4
gpt4 key购买 nike

我使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com