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

Chr*_*ady 4 c mathematical-expressions

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

Please choose an option below:
------------------------------
1. Linear time
2. Logarithmic time
3. Exponential time
Run Code Online (Sandbox Code Playgroud)

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

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

(choice==1)*n + (choice==2)*log(n) + (choice==3)*(n*n)
Run Code Online (Sandbox Code Playgroud)

在哪里n是要排序的数据集的大小,但这是不允许的.

chu*_*ica 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
Run Code Online (Sandbox Code Playgroud)

除非为0 (choice-2)*(choice-3)/((1-2)*(1-3)),choice==1否则通知 为1 .


该技术类似于多项式曲线拟合中的拉格朗日方法.