1

我已经把这段代码弄乱了一个多小时,试图以不同的方式重新排列它。有没有更简单的写法?

   if x is not Number      ;// if x is string
   {
      if y is not Number      ;// x, y both strings
      {
         Eval(x)
         Eval(y)
         return
      }
      else                    ;// x is string, y is Number
      {
         Eval(x)
         Scale(y)
         return
      }
   }
   else if y is not Number    ;// x is Number, y is string
   {
      Scale(x)
      Eval(y)
      return
   }
   else                       ;// both are numbers
   {
      Scale(x)
      Scale(y)
      return   
   }
4

2 回答 2

7

看起来你想要Eval字符串和Scale数字。x不要有四个明确的案例(这将变成八个带有三个变量的案例),而是独立地处理每个案例y

if x is Number
    Scale(x)
else
    Eval(x)

if y is Number
    Scale(y)
else
    Eval(y)

或者,更好的是,您可以将Eval/推Scale送到实用程序方法中:

ScaleOrEval(z):
    if z is Number
        Scale(z)
    else
        Eval(z)

...然后使用它...

ScaleOrEval(x)
ScaleOrEval(y)

如果您选择了好的方法名称,那么创建一个实用方法会使代码更具可读性,并帮助您避免复制和粘贴重复。

于 2010-08-26T08:04:07.030 回答
2
// First handle x
if x is Number
{
    Scale(x)
}
else
{
    Eval(x)
}

// Then handle y
if y is Number
{
    Scale(y)
}
else
{
    Eval(y)
}

return
于 2010-08-26T08:04:09.107 回答