简体   繁体   English

如何使函数返回C中多个变量类型的结果?

[英]How do I make a function return the result of multiple variable types in C?

Just started learning C from Cocoa developing guide and I was wondering how (if at all possible) I would return the result of a function with multiple variable types. 刚开始从Cocoa开发指南中学习C,我想知道如何(如果有可能)返回具有多个变量类型的函数的结果。 For example, I have a simple math function that I made to practice what I am reading and I gave it multiple variable types: 例如,我有一个简单的数学函数可以用来练习所阅读的内容,并为它提供了多种变量类型:

#include <stdio.h>

float doMath (int variable1, float variable2, int variable3, float variable4);

main()
{
    printf ("Math is fun!!\n");

    float theMath = doMath (2, 3.66, 9009, 7.990);
    printf ( "Result = %f\n", theMath );

}

float doMath (variable1, variable2, variable3, variable4) 
{
    return (variable1 * variable2) + (variable3 - variable4);
}

How would I utilize multiple variable types properly in a single function/equation? 如何在单个函数/方程式中正确利用多种变量类型? Also, I'm not sure the syntax of the return line is correct either...I sort of just took a stab at it. 另外,我也不知道返回行的语法是否正确……我只是在刺破它。

First, you don't put the function definition inside the main() function. 首先,不要将函数定义放在main()函数中。 Do it outside. 在外面做。 And you might want to put int main() instead of just main, and return 0 at the end of int main() 你可能想要把int main()而不仅仅是主要的,并return 0 ,在结束int main()

Then just assign a float variable to hold the result and return it. 然后,只需分配一个float变量即可保存结果并返回。

#include <stdio.h>

float doMath (int variable1, float variable2, int variable3, float variable4);

int main()
{
    printf ("Math is fun!!\n");

    float theMath = doMath (2, 3.66, 9009, 7.990);
    printf ( "Result = %f\n", theMath );

    return 0;
}

float doMath (int variable1, float variable2, int variable3, float variable4) 
{
    float answer = (variable1 * variable2) + (variable3 - variable4);
    return answer;
}

You can not return multiple types. 不能返回多种类型。 But you can return a union (or perhaps better still a structure containing a type indicator and a union). 但是您可以返回一个并集(或者最好还是包含一个类型指示器和一个并集的结构)。

typedef union {
   int i;
   float f;
} multi;
typedef struct {
   short type;
   multi m;
} multitype;

multitype f(int arg1, ...);

Of course, then you have to manage the polymorphism by hand. 当然,那么您必须手动管理多态性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM