【问题标题】:How to make a logical selection using calculations in c?如何使用 c 中的计算进行逻辑选择?
【发布时间】:2019-06-27 09:57:28
【问题描述】:

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

【问题讨论】:

  • 洛根问a comparable question;但是,他选择的解决方案是用特殊变量表示的。我们正在寻求更通用的解决方案。
  • 可以使用位运算符吗?
  • 不,不允许使用位运算符。
  • 教练说这些值永远只能是 1、2 或 3。
  • @ChrisHeady 这可能不是优化,这取决于。此外,很少需要编写无分支代码。

标签: c mathematical-expressions


【解决方案1】:

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

嗯 - 奇怪的限制


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

使用乘法、除法来影响== 的选择值choice 1、2、3。

(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))choice==1 时为1,否则为0。


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

【讨论】:

    【解决方案2】:

    使用

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

    其中 each 是返回 int 的 n 的函数。调用方式

     v = choice[I](n);
    

    【讨论】:

    • choice[I](n) 就够了
    【解决方案3】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2020-04-13
      • 1970-01-01
      • 2022-12-18
      • 2016-01-25
      • 2019-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多