定义值并通过数组调用它们
Defining values and calling them through an array
我试图写一个程序解决,通过蛮力,一个问题。
问题是由数组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
}
相关文章:
- 在调用接收数组的方法时,模板化数组大小是不是一种糟糕的做法
- 为什么调用堆栈数组会导致内存泄漏
- C++从函数指针数组调用函数
- 为什么静态数组成员变量在调用对象的实例后不显示任何内容?
- 如何在 c# 代码中通过引用调用时从 c++ dll 更新数组值?
- 调用函数后无法访问数组
- 使用数组数组调用 C++ 函数
- 为什么数组中对象的析构函数在被另一个对象替换时不被调用?
- 当数组位于两个循环之间时,您可以调用数组的 void 函数吗?
- 未调用数组的函数专用化
- 为什么只调用数组元素[3][..]或[4][..]会导致EXC_BAD_ACCESS
- 从c++中的结构数组中调用数组
- 如何调用数组的成员
- 调用数组中子类实例的方法
- 从同一类的另一个方法调用数组2D-C++
- c++析构函数调用数组索引?在非线程安全的refcount对象上崩溃
- 在c++中调用数组的成员以显示到控制台
- 在if/else语句中调用数组的成员
- 调用数组存储字符串类型从一个while到另一个while
- 在c++中使用枚举类值调用数组元素