定义值并通过数组调用它们

Defining values and calling them through an array

本文关键字:调用 数组 定义      更新时间:2023-10-16

我试图写一个程序解决,通过蛮力,一个问题。

问题是由数组n中的数字决定的(在本例中是1,2,3,4),我想对这些数字进行某种数学运算以得到值为10。

在这个例子中,使用数字1 2 3 4将得到1 + 2 + 3 + 4 = 10

在编写程序时,我不太确定如何检查我可以对数字执行的所有不同操作。我尝试定义操作,将每个值存储到数组中,然后遍历数组以找到解决方案。(

)

这是我的代码,我已经注释了我遇到的问题。

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define A +
#define B -
#define C *
#define D /
int main(void)
{
    char ops[3];  //Array to contain the different functions
    ops[0] = 'A';
    ops[1] = 'B';
    ops[2] = 'C';
    ops[3] = 'D';
    int n[3];    //Array containing the numbers which I'm trying to solve
    for(i = 0; i <= 3; i++)
    {
          n[i] = i;
    }
    int solution[2];   //Array which will keep track of the solution
    for(i = 0; i < 3; i++)
    {
        solution[i] = 0;
    }
    while(solution[2] <= 3)
    {
        while(solution[1] <= 3)
        {
            while(solution[0] <= 3)
            {
                //TROUBLE
                //Here I'm going to test it 
                //Was trying to do something like
                n[0] ops[solution[0]] n[1] etc. which should become 1 + 2 except it doesn't :/
            }
        }
    }

    sleep(5000);
    return 0;
}

那么,我如何将操作存储在某种数组中并调用它们呢?

您需要编写一个函数来完成此操作。宏是在编译整个程序之前处理的,所以它不能用于只有在运行时才知道的东西。

试试这个:

int solveOP(int op1, int op2, char op)
{
     switch (op)
     {
     case 'A': // or you can use '+' directly
         return op1+op2;
     case 'B':
         return op1-op2;
     // ...
     default: // when we've check all possible input
         // ERROR!
         // put your own error handling code here.
     }
}

当你需要使用它时,而不是n[0] ops[solution[0]] n[1],你说:

solveOP(n[0], n[1], ops[solution[0]]);

使用如下的switch语句:

switch(op)
{
   case 'A':
     val = a + b;
     break;
   case 'B':
     val = a - b;
     break;
   case 'C':
     val = a * b;
     break;
   ....
}

你正在寻找函数指针;你可以这样做:

typedef int (*op)(int, int);
#define opfunc(op, name) 
     void name(int a, int b){ return a op b; }
opfunc(+, plus)
opfunc(-, minus)
opfunc(/, div)
opfunc(*, times)
op ops[] = { plus, minus, times, div };
int main()
{
    //...etc, your code...
    int result = ops[x](something, somethingelse);
    // ...more code
}