通过代码减轻此功能的重量

del*_*amp -2 c c++ puzzle

考虑以下功能

  1. 额外费用4运营
  2. 分配成本1运营
  3. 比较成本1运营

计算上述功能将花费14次操作

int function1(int a,int b,int c, int d, int e)
{
int returnNumber;
//int no = randomNumber(); //Some Random Number Generator Function , Lets Assume the cost of this function to be 0 for simplicity purpose

switch(randomNumber())
   {
   case 0: returnNumber = a+b;  // costs 6 Operations , Case Check costs 1, assignment costs 1 and addition costs 4
           break;
   case 1: returnNumber = c+d;  // Costs 6 Operations 
           break;
   default: returnNumber = e;   // costs 2 Operations
   }
 return returnNumber;
}
Run Code Online (Sandbox Code Playgroud)

这个功能的总成本是14个操作,是否有任何代码可以做同样的事情,并且至少将此功能的成本降低1?

编辑1 在开关语句中添加了Break语句以及将变量no赋值给randomNumber生成器函数

编辑2我从我的一个朋友那里碰到了这个问题,碰巧在F2F中遇到了这个问题,我想知道这个问题是否有解决方案,因为我还没有找到任何直到现在.

jam*_*lin 8

如最初编写的那样,该switch块没有break语句,因此无论生成的随机数如何,返回的值始终是最后一种情况的结果.因此整个功能可以简化为:

int function1(int a,int b,int c, int d, int e)
{
   return e;
}
Run Code Online (Sandbox Code Playgroud)

当前版本可以调整为:

int function1(int a,int b,int c, int d, int e)
{
    switch(randomNumber())
    {
       case 0: return a+b;
       case 1: return c+d;
       default: return e;
    }
}
Run Code Online (Sandbox Code Playgroud)

根据您的指标,每个案例可以减少一个变量分配.(但是,任何体面的编译器都会对它进行优化.)