MATLAB:循环内的 If 语句未执行,也未打印到屏幕
因此,我们尝试执行以下代码。两个 if 语句正在执行,但是内部的 if 语句无法执行(我们通过不抑制输出来验证这一点)。有理由吗?或者我们只是无法达到这种状态?
规格
输入如下:v是int值的向量,c是整数。 c 必须小于或等于 v 中的值之一
我们试图用该算法解决的问题如下:
给定一个收银机,如何找零才能用最少的硬币 可能会退回给客户吗?
例如:输入:v = [1, 10, 25, 50],c = 40。输出 O = [5, 1, 1, 0]
我们只是在寻找不是更好的解决方案,而是更多地寻找该部分的原因该代码没有执行。
function O = changeGreedy(v,c)
O = zeros(size(v,1), size(v,2));
for v_item = 1:size(v,2)
%locate largest term
l_v_item = 1
for temp = 2:size(v,2)
if v(l_v_item) < v(temp)
l_v_item = temp
end
end
%"Items inside if statement are not executing"
if (c > v(l_v_item))
v(l_v_item) = -1 %"Not executing"
else
O(l_v_item) = idivide(c, v(l_v_item)) %"Not executing"
c = mod(c, v(l_v_item)) %"Not executing"
end
end
So, we are trying to execute the following code. The two if statements are executing, however, the inside if statements are failing to execute (we verified this by not suppressing the output). Is there a reason why? Or are we just not able to reach this state?
Specifications
The input is as follows: v is a vector of int values and c is a integer. c must be less than or equal to one of the values within v
The problem that we are trying to solve with this algorithm is as follows:
Given a cash register, how does one make change such that the fewest coins
possible are returned to the customer?Ex: Input: v = [1, 10, 25, 50], c = 40. Output O = [5, 1, 1, 0]
We are just looking for not a better solution but more of a reason why that portion of the code is not executing.
function O = changeGreedy(v,c)
O = zeros(size(v,1), size(v,2));
for v_item = 1:size(v,2)
%locate largest term
l_v_item = 1
for temp = 2:size(v,2)
if v(l_v_item) < v(temp)
l_v_item = temp
end
end
%"Items inside if statement are not executing"
if (c > v(l_v_item))
v(l_v_item) = -1 %"Not executing"
else
O(l_v_item) = idivide(c, v(l_v_item)) %"Not executing"
c = mod(c, v(l_v_item)) %"Not executing"
end
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果
c
或v
不是整数,即class(c)
计算结果为double
,那么我得到以下结果错误消息并且程序停止执行。因此,第二条语句的内部永远不会执行。相反,如果 c 是一个整数,例如 uint8 类,则一切都会正常执行。
另外:您实际上想用这段代码实现什么目的?
If
c
orv
are not integers, i.e.class(c)
evaluates todouble
, then I get the following error messageand the program stops executing. Thus, the inside of the second statement never executes. In contrast, if, say,
c
is an integer, for example of classuint8
, everything executes just fine.Also: what are you actually trying to achieve with this code?
尝试对您的输入数据执行此操作:
然后再次运行,至少代码的某些部分将执行。
idivide
引发了一个错误,显然您错过了:确实,
idivide
似乎要求您有实际整数输入数据(即、class(c)
和class(v)
均计算为整数类型,例如int32
)。Try to do this operation on your input data:
and run again, at least some portions of your code will execute. There is an error raised by
idivide
, which apparently you missed:Indeed,
idivide
seems to require that you have actual integer input data (that is,class(c)
andclass(v)
both evaluate to an integer type, such asint32
).