如何返回多个值,并将其存储在main()函数? [英] How to return multiple values and store them in main() function?

查看:97
本文介绍了如何返回多个值,并将其存储在main()函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个函数返回两个或多个值,并希望将这些值存储到的main()功能。我想通过以下code做到这一点。

I want to return two or more values from a function and want to store those values into the main() function. I'm trying to do this by following code.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int num1, num2, s, p;
    printf("Enter tow numbers: ");
    scanf("%d %d", &num1, &num2);
    p = function(num1, num2);
    s = function(num1, num2);
    printf("Sum is: %d\nProduct is: %d", p, s);
    return 0;
}

int function(int x, int y)
{
    int sum, product;
    sum = x+y;
    product = x*y;
    return product, sum;
}

如果我输入两个数字,说 5 2 我想我的结果是:

If I enter two numbers, say 5 2 I want my result to be:

Sum is: 7
Product is: 10

但我发现了两个7。我怎样才能得到我想要的输出?

But I'm getting 7 for both. How can I get my desired output?

推荐答案

C不会允许你定义它返回多种类型或单一类型的多个实例的功能。您可以使用捆绑然而,相似或不同类型的变量组合成一个新的用户定义类型结构。在这种情况下,你会做这样的事情:

C does not permit you to define a function which returns multiple types or multiple instances of a single type. You can however bundle variables of similar or disparate types together into a new user-defined type using a struct. In this case, you would do something like:

#include <stdio.h>
#include <stdlib.h>

typedef struct myStruct {
    int sum;
    int product;
} myStruct;

myStruct function(int x, int y) {
    myStruct val;
    val.sum = x+y;
    val.product = x*y;
    return val;
}

int main() {
    int num1, num2;
    myStruct result;
    printf("Enter tow numbers: ");
    scanf("%d %d", &num1, &num2);
    result = function(num1, num2);
    printf("Sum is: %d\nProduct is: %d", result.sum, result.product);
    return 0;
}

此外,尽管上述程序在语法上是正确的,在函数的返回有只有逗号分隔值的集合中返回的最后一个值的结果。通常情况下,不使用收益一起使用;然而,在一个循环使用时,它可以很方便。

Also, while your program above is syntactically correct, the , in the return of your function has the result of only returning the last value in the collection of comma separated values. Normally the , isn't used in conjunction with a return; it can be quite handy when used in a for loop however.

这篇关于如何返回多个值,并将其存储在main()函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆