I would like to pass multiple different variables through one function that returns a single value/output. The only way I can think to do this is to call the function for each value that needs to pass through it.
我想通过一个返回单个值/输出的函数传递多个不同的变量。我能想到的唯一方法是为每个需要通过它的值调用函数。
eg.
例如。
int foo = 9;
int doo = 4;
int yoo = 23;
convertIntToSomethingElse(foo);
convertIntToSomethingElse(doo);
convertIntToSomethingElse(yoo);
I've got a strong feeling this is bad programming and that there is a more efficient way of doing this.
我有一种强烈的感觉,这是糟糕的编程,并且有一种更有效的方法来做到这一点。
1 个解决方案
#1
1
Since you asked for an example.
既然你问了一个例子。
There are 2 ways to do this:
有两种方法可以做到这一点:
First, is to pass the entire array to a function and then do things with those multiple times inside the array:
首先,是将整个数组传递给一个函数,然后在数组中多次执行这些操作:
int yourArray[3] = {9, 4, 23};
//get the number of elements in the array by dividing total size by a
//size of a single element
//if you know the size you can just use that, but it's not reccomended
size_t n = sizeof(a)/sizeof(a[0]); //Pass this to function to get array size
void yourFunction (int a[], int sizeOfArray){
int i;
for(i=0;i<sizeOfArray;i++){
//do stuff you need
}
}
The second way is to just run the function multiple times in the array using a loop:
第二种方法是使用循环在数组中多次运行该函数:
for(i=0; i<n; i++){
yourFunction(yourArray[i]);
}
#1
1
Since you asked for an example.
既然你问了一个例子。
There are 2 ways to do this:
有两种方法可以做到这一点:
First, is to pass the entire array to a function and then do things with those multiple times inside the array:
首先,是将整个数组传递给一个函数,然后在数组中多次执行这些操作:
int yourArray[3] = {9, 4, 23};
//get the number of elements in the array by dividing total size by a
//size of a single element
//if you know the size you can just use that, but it's not reccomended
size_t n = sizeof(a)/sizeof(a[0]); //Pass this to function to get array size
void yourFunction (int a[], int sizeOfArray){
int i;
for(i=0;i<sizeOfArray;i++){
//do stuff you need
}
}
The second way is to just run the function multiple times in the array using a loop:
第二种方法是使用循环在数组中多次运行该函数:
for(i=0; i<n; i++){
yourFunction(yourArray[i]);
}