函数将多值返回给主函数

时间:2018-11-09 16:13:50

标签: c return

此代码是我的主代码的一部分,在此部分中,用户输入的每个产品代码,数量和总价都会增加,最后,用户将totalSum,quantity1,quantity2,quantity3,quantity4返回给main功能,然后继续打印收据,我知道要返回主功能必须这样做z= getTotalSum()。但是如何获得多收益? (目前我设置为0,因为我不知道如何放置)

#include <stdio.h>
int getTotalSum (void); // when user selected product will calculate sum,quantity of each product
int main ()
{
getTotalSum();
return 0;
}
int getTotalSum (void)
{
int code;
float sum=0,totalSum,quantity1=0,quantity2=0,quantity3=0,quantity4=0;
while(1)
{   
    printf("Enter a product code.(Enter 5 to get total sum)\n");
    scanf("%d",&code);

    switch(code)
    {
    case 1:
        {
        quantity1=( quantity1 + 1);
        sum=( 45.20 + sum);
        printf("Current Sum: RM%.2f\n",sum);
        break;
        }
    case 2:
        {
        quantity2=( quantity2 + 1);
        sum=(14.50 + sum);
        printf("Current Sum: RM%.2f\n",sum);
        break;
        }
    case 3:
        {
        quantity3=( quantity3 + 1);
        sum=(3.45 + sum);
        printf("Current Sum: RM%.2f\n",sum);
        break;
        }
    case 4:
        {
        quantity4=( quantity4 + 1);
        sum=(7.80 + sum);
        printf("Current Sum: RM%.2f\n",sum);
        break;
        }
    case 5:
        totalSum= sum;
        printf("+--------------+--------------------+----------+\n");
        printf("| Product Code | Rentail Price (RM) | Quantity |\n");
        printf("+--------------+--------------------+----------+\n");
        printf("| 1            | 45.20              | %.f        |\n",quantity1);
        printf("+--------------+--------------------+----------+\n");
        printf("| 2            | 14.50              | %.f        |\n",quantity2);
        printf("+--------------+--------------------+----------+\n");
        printf("| 3            |  3.45              | %.f        |\n",quantity3);
        printf("+--------------+--------------------+----------+\n");
        printf("| 4            |  7.80              | %.f        |\n",quantity4);
        printf("+--------------+--------------------+----------+\n");
        printf("Total Sum: RM%.2f\n",totalSum); 
        return 0;
    }
    }
}

1 个答案:

答案 0 :(得分:3)

您可以采用多种方法来return多个值:

  1. returnstruct
  2. 写一些通过地址传递给函数的变量
  3. 写入struct,并按地址传递给函数
  4. 写入传递给函数的数组

每个示例如下:

1

struct data
{
    int one;
    int two;
    int three;
    int four;
};

struct data getTotalSum(void)
{
    ...
}

2

void getTotalSum(int *one, int *two, int *three, int *four)
{
    ...
}

3

struct data
{
    int one;
    int two;
    int three;
    int four;
};

void getTotalSum(struct data *d)
{
    ...
}

4

void getTotalSum(int *array)
{
   ...
}