如何在 While 循环中有两个条件? [英] How to have two conditions in a While loop?

查看:50
本文介绍了如何在 While 循环中有两个条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我的代码中有两个 while 循环.他们所做的只是从 0 到 10 或 -10 以 1 的增量计数.计数的向量是count1"和count2".这发生在我的代码中的两个单独的 while 循环中.但是,我现在需要每个计数相互依赖,因此我需要在同一个循环中使用它们.是否可以让两个独立的 while 条件在一个循环中工作.例如,我现在拥有的是:

Basically I have two while loops in my code. All they do is count in increments of 1 from 0 to either 10 or -10. The vectors that count are "count1" and "count2". This is happening in my code in two separate while loops. However, I now need each count dependent on each other so I need them within the same loop. Is it possible to have the two separate while conditions working in one loop. For example, what I have now is:

  count1 = 0
  count2 = 0
  l_RWM = vector()
  r_RWM = vector()      


while (count1 < 10 && count1 > -10){

  count1 = count1 + (sample(c(1,-1), 1, prob = c(.55,.45)))

  l_RWM = append(l_RWM,count1)

}

while (count2 < 10 && count2 > -10){

  count2 = count2 + (sample(c(1,-1), 1, prob = c(.55,.45)))

  r_RWM = append(r_RWM,count2)

}

但我想要类似的东西

while (count1&count2 < 10 && count1&count2 > -10){

if(count1 < 10 && count1 > -10) count1 = count1 + (sample(c(1,-1), 1, prob = c(.55,.45)))
    else count1 = count1

  if(count2 < 10 && count2 > -10) count2 = count2 + (sample(c(1,-1), 1, prob = c(.55,.45)))
    else count2 = count2

    l_RWM = append(l_RWM,count1)
    r_RWM = append(r_RWM,count2)

 }

我的if"代码应该只在对象未达到 10 或 -10 时才会发生计数.例如.即使 count1 完成,count2 仍会向上或向下计数.我的代码不起作用,我不是在寻找答案,而是寻找为什么不起作用的原因.请记住,我对 R 很陌生,如果这个问题微不足道,我提前道歉:p.

My "if" code is supposed to only have the count occur when the object hasn't reached 10 or -10. E.G. count2 will still count up or down even when count1 has finished. My code doesn't work and I am not looking for an answer but more so a reason to why it doesn't. Keeping in mind that I am very new to R and I apologise in advance if this question is trivial :p.

对于任何想知道的人,我在同一个循环中需要它们的原因是因为我希望有类似的东西:如果 count1 增加而不是 count2 减少.

For anyone wondering, the reason I need them in the same loop is because I'm looking to have something like: if count1 increases than count2 decreases.

谢谢

推荐答案

我假设,根据你的伪代码,你只是想确保 count1 和 count2 都小于 10 并且 count1 和 count2 大于-10.我会做的是这样的:

I am assuming, from your pseudo code, that you are just wanting to make sure both count1 and count2 are less than 10 and that count1 and count2 are greater than -10. What I would do is something like this:

while (count1 < 10 && count2 < 10 && count1 > -10 && count2 > -10){

您不需要用括号将任何内容分组,因为所有内容都是 AND 组合在一起的,并且没有混合逻辑.

You shouldn't need to group anything with parenthesis since everything is ANDed together and there is no mixed logic.

这篇关于如何在 While 循环中有两个条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆