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

心已入冬 提交于 2020-01-07 05:37:06

问题


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. 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.


回答1:


First, you don't put the function definition inside the main() function. Do it outside. And you might want to put int main() instead of just main, and return 0 at the end of int main()

Then just assign a float variable to hold the result and return it.

#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;
}



回答2:


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.



来源:https://stackoverflow.com/questions/3852166/how-do-i-make-a-function-return-the-result-of-multiple-variable-types-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!