(我能够用数组的输出来解决前面的问题,一切都完成了)。
我这里有一段代码,我想为它编写一个函数来缩短代码。但我不知道怎么做,因为,很显然,它需要返回两个值,我不知道怎么做.
或者我应该把这个动作分解成两个不同的功能?
还是把代码留在这个表格里比较好?
int a2x = 0;
int m2x = 0;
for (i = 0; i < n; i++) {
if (x[i] > 0) {
a2x = a2x + x[i];
}
if (x[i] < 0) {
m2x++;
}
}
printf("\n");
printf("a2x %5d \n", a2x);
printf("m2x %5d \n", m2x);
int a2y = 0, m2y = 0;
for (j = 0; j < m; j++) {
if (y[j] > 0) {
a2y = a2y + y[j];
}
if (y[j] < 0) {
m2y++;
}
}
printf("a2y %5d \n", a2y);
printf("m2y %5d \n",m2y);发布于 2020-12-24 15:04:45
您可以使用以下返回类型的函数:
struct ReturnType
{
int a2y;
int m2y;
};这种类型反映了它是一对值,而不是同一个值的两个实例。也就是说,它是一个X和一个M,不是两个X和两个Xs,它的行为也像一个可复制的变量,就像返回一个int。
发布于 2020-12-24 15:00:10
我向你提出我认为最简单的3种选择:
I)在函数中打印结果。
这样,不仅不需要返回变量,还可以在函数中直接声明变量。
II)通过引用传递变量。
这样,函数实际上可以更改它们的值,因此不需要返回任何内容。
III)分配一个数组,存储要返回的值,并返回该数组。
通过这种方式,您可以返回任意数量的值。
编辑:正如Andrew在对Yunnosch的回答的评论中所建议的:“返回一个结构或传递一个数组的地址可能在性能上几乎是相同的,所以在这一点上它是一个风格/偏好/清晰度/O&M问题,这使得它非常依赖于上下文。”
而且,正如Yunnosch所指出的那样,有了一个结构,你可以给每个元素一个不同的含义,所以在你的情况下,使用一个结构更合适。
发布于 2020-12-24 16:06:38
从技术上讲,还有一种以前没有提到的方法:以更大的整数类型传递它:
#include <limits.h>
#define HIGHEST_UINT_BIT ((UINT_MAX>>1)+1)
#define HIGHEST_ULLINT_BIT ((ULLONG_MAX>>1)+1)
#if HIGHEST_ULLINT_BIT/HIGHEST_UINT_BIT/HIGHEST_UINT_BIT<2
#error "unsigned long long int not large enough to hold 2 int variables"
#endif
//returns the integer a in higher half of the returning long long int
//and the integer b in the lower half of the returning long long
unsigned long long int foo(void)
{
int a=42; //set a to any integer value you like
int b=0x42; //same for b
//pack a and b into the return value
//<<(sizeof(int)*CHAR_BIT) shifts a to the higher half of r
unsigned long long int r=((unsigned long long)a)<<(sizeof(int)*CHAR_BIT);
r|=(unsigned)b;
return r;
}
#include <stdio.h>
int main(void)
{
unsigned long long int r=foo();
//extract a and b from r
int a=r>>(sizeof(int)*CHAR_BIT);
int b=r&UINT_MAX;
printf("a is %i (0x%X) b is %i (0x%X)\n",a,(unsigned)a,b,(unsigned)b);
return 0;
}但你不应该用这种方法。因为它不能扩展到更多的变量,所以只有当整数类型的大小是2倍或更大时,它才能工作,它只对整数起作用,而且它是一个黑客。最好使用其他答案中提到的pointer方法。
https://stackoverflow.com/questions/65439886
复制相似问题