如何判断变量是否为偶数而不是零?

问题描述 投票:0回答:1

我不知道如何检查变量是否为偶数,但大于零。是否可以为一个语句添加 2 个条件?下面的说法有错吗?

> if (i %% 2 == 0 & i > 0){
  P_lastround = f-(i/2*P_even + ceiling((i-1)/2)*P_odd)
  Fraction = P_lastround/P_even
} else if (i %% 2 != 0 & i > 0){ 
  P_lastround = f-(P_even*((i-1)/2) + P_even + floor(i/2)*P_odd)
  Fraction = P_lastround/P_odd
} else (i==0) 
{
  P_lastround = f
  Fraction = P_lastround/P_even
}    

我尝试了很多不同的 i 值,但总是得到相同的答案。

R 只读取我的 else(语句 3),即使它不适用。

r if-statement multiple-conditions
1个回答
0
投票

以下工作正常:

test <- function(i) {
  if (i %% 2 == 0 & i > 0) {
    "even"
  } else if (i %% 2 != 0 & i > 0) { 
    "odd"
  } else {
    "zero"
  } 
}

test(0)
[1] "zero"
test(1)
[1] "odd"
test(2)
[1] "even"
© www.soinside.com 2019 - 2024. All rights reserved.