C 程序 : converting an if statement code to a code which does not use logical, 关系运算符或选择结构(允许 NO 开关)

标签 c arrays if-statement switch-statement logical-operators

我用 C 写了这段代码。它相当简单易懂。如何将程序末尾的 if 语句转换为不使用任何类型的逻辑或关系运算符、任何选择结构或任何数组的语句?这意味着 if 语句必须转换为简单的算术代码。

#include<stdio.h>
#include<math.h>

int main (void)
{
    //Declarations

    int m;  //mass of the object
    int vi; //initial velocity of the object
    int ur; //coefficient of resistance
    int choice; //choice
    double net_force; //net force acting on the object
    double force_grav; //force due to gravity only
    double force_res; //force due to the resistance only
    double force_des; //Desired force in output section

    #define g 9.8

    //Input statements
    printf("Please input the mass in kilograms:");
    scanf("%d",&m);
    printf("Please input the launch speed (m/s):");
    scanf("%d",&vi);
    printf("Please input the coefficient of resistance (kg/s):");
    scanf("%d",&ur);

    //Executable Statements
    printf("Choices for calculation:\n");
    printf("1. Force due to gravity only\n");
    printf("2. Net force\n");
    printf("3. Force due to resistance only\n");
    printf("Please enter your choice: ");
    scanf("%d", &choice);

    //Calculations
    force_grav = m * g;
    force_res = (-1) * ur * vi;
    net_force = force_res + force_grav;


    if(choice==1)
        printf("Desired force: %2.3lf", force_grav);
    else
        if(choice==2)
            printf("Desired force: %2.3lf", net_force);
        else
            printf("Desired force: %2.3lf", force_res);

   return(0);
}

最佳答案

如果问题应该通过算术解决,我的建议是:

force_grav = m * g;
force_res = (-1) * ur * vi;
net_force = force_res + force_grav;

force = force_grav*(2-choice)*(3-choice)/2 + 
        force_res*(1-choice)*(2-choice)/2  +
        net_force*(1-choice)*(3-choice)*(-1);

printf("Desired force: %2.3lf", force);

变量“choice”现在有效地选择,哪些被加数对项的结果有贡献。

这个术语当然可以简化,但我让它“按原样”来展示这个概念。

关于C 程序 : converting an if statement code to a code which does not use logical, 关系运算符或选择结构(允许 NO 开关),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42071217/

相关文章:

c - 我的排序功能出了什么问题

c - 测试#define CONSTANT

c - 在结构定义内的函数指针内使用 void* 作为参数会导致语法错误

c - 选择排序不排序

Python:如何使用字符串索引( '[0][1][0]')作为多维数组的索引

mysql - 无法使 IF ELSE IF 语句起作用

java - 如果两者都被评估,比较文字的顺序是否重要?

c - GETS - C 不适合我

sql-server-2008 - 尽管满足条件但 T-SQL IF block 不执行

javascript - 将列(对象的对象)转换为行(对象的数组)