如何使用c中的计算进行逻辑选择?

时间:2019-02-03 12:41:50

标签: c mathematical-expressions

我正在帮助我的女儿进行c编程介绍,她的作业包含一个简单的菜单,如下所示:

Please choose an option below:
------------------------------
1. Linear time
2. Logarithmic time
3. Exponential time

现在,通常通常很容易确定菜单选项是什么,但是不允许她使用逻辑运算符,关系运算符,按位运算符或选择构造。我们一直在尝试使用模数,但无济于事。这有可能吗?她基本上只能使用+, -, *, /, and %。以及简单的变量。

到目前为止,我们提出的唯一解决方案是使用相等性:

(choice==1)*n + (choice==2)*log(n) + (choice==3)*(n*n)

其中n是要排序的数据集的大小,但这是不允许的。

3 个答案:

答案 0 :(得分:5)

  

仅使用+,-,*,/和%

嗯-奇怪的限制


代替(choice==1)*foo1 + (choice==2)*foo2 + (choice==2)*foo3

使用乘法,除法对== 1,2,3的选择值使用choice

(choice-2)*(choice-3)/((1-2)*(1-3)) * foo1 + 
(choice-1)*(choice-3)/((2-1)*(2-3)) * foo2 + 
(choice-1)*(choice-2)/((3-1)*(3-2)) * foo3

通知(choice-2)*(choice-3)/((1-2)*(1-3))为1,而choice==1为0。


这项技术类似于多项式曲线拟合中的https://i.imgur.com/4lLIEmC.png

答案 1 :(得分:3)

使用

always @(posedge CLOCK_50 or posedge RESET)
begin
   if (RESET == 1'b1)
   begin 
      COUNT2 <= 2'd00;
      dashflag <= 1'b0;
   end // reset
   else if (halfsecflag) // or  if (halfsecflag==1'b1)
   begin     
      if (COUNT2==2'd2))
      begin
         COUNT2 <= 2'd0;
         dashflag <=1'b1;
      end
      else
      begin
         COUNT2 <= COUNT2+2'd1;
         dashflag <=1'b0;
      end
   end // clocked 
end // always 

其中每个是n返回一个int的函数。通过

致电
int (* choice[3])(int n) = { linear, log, exp };

答案 2 :(得分:0)

如果计算复杂一点,可能很难在一个操作中完成。然后使用函数指针:

double linear(double x)
{
    double result;
    /* some cacls */
    return result;
}

double logarithmic(double x)
{
    double result;
    /* some cacls */
    return result;
}

double expotential(double x)
{
    double result;
    /* some cacls */
    return result;
}


double (*calcfunc[])(double) = {linear, logarithmic, expotential};


double calc(int choice, double x)
{
    return calcfunc[choice](x);
}

我希望允许使用数组:) 非常奇怪的要求-除不良做法外,它不会教任何东西。参数和返回类型就是示例。