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

How to make a logical selection using calculations in c?

我正在帮我女儿做一个 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 是要排序的数据集的大小,但这是不允许的。

only use +, -, *, /, and %

嗯 - 奇怪的限制


而不是(choice==1)*foo1 + (choice==2)*foo2 + (choice==2)*foo3

使用乘法、除法对 choice 1,2,3 的 select 值产生 ==

(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.


此技术类似于多项式曲线拟合中的The Lagrange method

使用

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

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

调用
 v = choice[I](n);

如果计算稍微复杂一点,一次操作可能难以完成。然后使用函数指针:

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);
}

我希望数组是允许的:) 非常奇怪的要求 - 它没有教任何东西,除了不好的做法。参数和 return 类型当然是示例。