2014-03-19 47 views
0

我有这样的工作,似乎像一个ATM,但我的问题是我想更新余额,但我不能。例如,当我第一次检查余额时,它会给出“0”,那么如果我再次存入“200”时,我再次检查余额,现在给我“200”,然后如果我想撤回“100”当我检查余额时,应该给我“100”。但我在传递函数中的值时遇到了问题。这是我的工作。请帮帮我。哦顺便说一句,即时通讯使用DEV C +Turbo C在函数中传递值

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

// Declaring Functions that exist in the program. 

    int menu(); 

// End 

// Main method at top, just to help with readability. And it can use the functions since we have already told main they exist. 
    int main() 
    { 
    int a = 0; 
    int option; 
    int atmDeposit(); 
    int atmWithdrawal(int balance); 
    int atmCheck(int z); 

    system("cls"); 
    do 
    { 
     option = menu(); 
     switch(option) 
     { 
      case 1: 
       atmDeposit(); 
       break; 
      case 2: 
       atmWithdraw(a); 
       break; 
      case 3: atmCheck(a); 
       break; 
      case 4: 
       printf("\nGoodbye!"); 
       system("pause"); 
       exit(0); 
      default: 
       printf("\nInvalid!\n"); 
       break; 
     } 
    } 
    while (option != 4); 

    getch(); 
    return 0; 
} 

int menu() 
{ 
    int op; 
    system("cls"); 

    printf("What do you want to do?: \n"); 
     printf("1 - Deposit\n"); 
     printf("2 - Withdraw\n"); 
     printf("3 - Check Balance\n"); 
     printf("4 - Exit\n\n"); 

     printf("Enter Choice: "); 

     scanf("%d",&op); 
    return op; 

} 
// End 

// to check balance 
int atmCheck(int z) 
{ 

    printf("\nYour Balance is P%d\n",z); 
    system("pause"); 
    return z; 
} 
// End check balance 

// to Deposit 
int atmDeposit() 
{ 
    int deposit, a=0; 

    printf("\nHow much money do you want to deposit?: P"); 
    scanf("%d", &deposit); 

    a += deposit; 

    printf("%d",a); 
    system("pause"); 


    return a; 
} 
// end deposit 

// to withdraw 
int atmWithdraw(int balance) 
{ 
    int withdraw; 

    printf("\nHow much money do you want to withdraw?: P"); 
    scanf("%d", &withdraw); 

    balance -= withdraw; 
    printf("%d",balance); 
    system("pause"); 

    return balance; 
} 
// end withdraw 
+0

当您在存款后检查余额时,您确定它会给您200吗?它给了我0。 –

回答

0

这里有几个错误。首先,您的提款和存款功能中使用的变量仅限于这些功能。因此,下次您要求用户提交选择并执行操作时,上次分配的值将丢失。

您可以通过使用main中声明的变量a来解决此问题,以存储余额,然后在其他函数中对其执行操作。但是,如果在main中声明变量(也是函数),则在其他函数中将不会识别变量。所以,你需要声明它之外main,像这样:

int menu(); 
int a = 0; 

int main() 
{ 
... 
} 

接下来,在你的atmDeposit功能,您声明一个局部变量a。当您将存款金额添加到该金额时,该值仅在该迭代中保留。当您下次要求用户输入选项时,该变量将重置为0,您之前的更改将丢失。所以,摆脱局部变量并使用如上所述声明的全局变量。 atmWithdrawatmCheck函数需要相同的修复 - 从余额减去全部变量的存款并返回。

最后,我不确定为什么你需要这些函数的输入参数,因为你从用户的输入参数存取。所以,删除功能的输入参数。另外,如果您只是在每种情况下在屏幕上显示新的余额,我不确定为什么要返回值。所以,你的函数签名想:

void atmDeposit(); 
void atmWithdraw(); 
void atmCheck(); 
0

1)声明你的变量int a=0;全球(即,主要功能外 - 如下)。这允许所有功能访问公共变量。

int a=0; 

int main() 
{ 
    ... 

2)在功能int atmDeposit()除去声明a=0;

3)在功能int atmWithdraw(int balance)之前system("pause");

a = balance; 

随着这些改变程序工作添加以下行