2014-10-17 71 views
-2

我正在尝试使用全局变量禁止使用的项目。在我的项目,我有以下功能:如何使用函数中的值C

int addAccount() 
{ 
    int ID_number = 0; 
    int ID; 
    int ID_array[10]; 
    double account_balance; 
    double balance_array[10]; 
    int choice = getChoice(); 
    if (choice == 1) 
    { 
     if (ID_number + 1 > 10) 
     { 
     printf("Error\n"); 
     } 
     else 
     { 
     ID_number = ID_number + 1; 
     printf("Please enter the id\n"); 
     scanf("%d", &ID); 
     ID_array[ID_number - 1] = ID; 
     printf("Please enter the starting balance\n"); 
     scanf("%lf", &account_balance); 
     balance_array[ID_number - 1] = account_balance; 
     } 

    } 
    return; 

我需要以某种方式获得的值数这些变量并在另一个功能(特别是ID,ID_NUMBER和account_balance)使用它们。我需要这些值的功能如下:

void displayAccounts() 
{ 
    int count; 
    int choice = getChoice(); 
    int ID_number = ID_number(); 

    if (choice == 2) 
    { 
     for (count = 0; count < ID_number; count++) 
     { 
     printf("Account #%d: ID is %d\n", count + 1, ID_array[count]); 
     printf("Account balance is %.2lf\n", balance_array[count]); 
     } 

    } 
} 

我知道如何返回一个值,但我不知道如何使多个值,其中它们发生的功能可用之外。我试图甚至可能做什么,或者可能是我以错误的方式讨论我的项目?

+0

'返回ID_VALUE;'而不是只'return;'(这会引发至少一个警告,因为函数返回int) – joop 2014-10-17 10:02:19

+0

在C中,函数只能返回一个值。对于你的问题,你可以去存储在一个数组中的值,然后将该数组返回到调用函数。 – Haris 2014-10-17 10:02:36

+1

使用指针,然后可以使用不同函数中的更新值... – 2014-10-17 10:02:40

回答

2

使用struct

struct Account 
{ 
    int count; 
    int ID_number; 
    int balance_array[10]; 

    // etc etc 
}; 

一个指针传递给addAccount

void addAccount(struct Account *account) 
{ 
    account->ID_number = 0; 
    // etc 
} 

然后把它传递给displayAccounts

void displayAccount(struct Account *account) 
{ 

} 

如:

struct Account account; 
addAccount(&account); 
displayAccount(&account); 

请注意,在C中,您需要使用struct前缀,除非您的结构为typedef

+0

当我尝试实现这一点时,我得到了错误“错误:未知类型名称'帐户'”在行“void addAccount (Account * account)“ – Titanguy654 2014-10-17 12:43:47

+0

对不起,我的错误是,我遗漏了几个地方的'struct'关键字。 – Sean 2014-10-17 13:27:17

2

最明显的选择是创建一个struct,它可以包含任意数量的字段(包括数组),并且可以传递给函数并将其返回。这样你就可以传递必要的状态。

你当然也可以通过让一个根函数定义结构变量来优化它,然后将指针传递给同一个实例。