Thread: having trouble with functions

  1. #1
    Registered User
    Join Date
    Oct 2011
    Posts
    13

    having trouble with functions

    Hey everyone,

    I am having trouble with writing a program that uses functions. I am very new to programming and am having a hard time grasping some concepts.

    What I need to do is write a series of functions to prompt the user for some input, then I need to return that input to the main then use it in another function to do some calculations then return the calculations back to the main and print the results in another function.

    I can't get my spacing to format in the code tags but hopefully it is still readable.

    Also I know its incomplete I had it working while using integers but I need to have 2 decimals for my numbers so I deleted some things to go back and try and debug.

    Any help would be appreciated

    Code:
    #include <stdio.h>
    
    int accno();
    double balance();
    double purchase();
    double payment();
    double credit(); 
    double iendbal();
    double accint();
    double fendbal();
    printfun();
    
    
    int main ()//main function
    {
    //gather information from functions
    int acc = 0;
    double bal;
    double pur;
    double pay;
    double cr;
    double interest;
    double interim;
    double final;
    int tcust;
    double  totfeb;
    static counter = 1;
    
    acc = accno();
    bal = balance(); 
    pur = purchase();
    pay = payment();
    cr = credit();
    
    interim = iendbal(&bal, &pur, &pay, &cr);
    
    interest = accint(&interim);
    
    final = fendbal(&interest, &interim);
    
    printfun(&acc,&bal,&pur,&pay,&cr,&interest,&final);
    
    
    return 0;
    }
    int accno()
    {
        int x;
            printf("Account Number(between 1000 and 4000 only) - Enter -9999 to Quit: ");
            scanf("%d", &x);
    
                if(x >= 1000 && x <= 4000)
                    return (x);
                    else if( x== 9999)
                        return test();
                        else 
                            return printf("Invalid Account Number. Please Try Again\n\n"); accno();
    }
    double balance ()
    {
        double x;
            printf("Beginning Balance: ");
            scanf("%lf", &x);
    
        return (x);
    }
    
    double purchase()
    {
        double x;
            printf("Purchases: ");
            scanf("%lf", &x);
    
            if(x >= 0)
                return (x);
            else 
                return printf("Invalid Entry. Please Try Again\n\n"); purchase();
    }
     
    double payment()
    {
        double x;
            printf("Payments: ");
            scanf("%lf", &x);
    
        if(x >= 0)
            return (x);
        else 
            return printf("Invalid Entry. Please Try Again\n\n"); payment();
    
    }
    
    double credit ()
    { 
        double x;
            printf("Credits/Returns: ");
            scanf("%lf", &x);
    
        return (x);
    }
    
    double iendbal(x, y, z, a)
    {
        return x + y - z - a;
    }
    
    double accint(x)
    {
        return x * .14;
    }
    
    double fendbal(x,y)
    {
        return x + y ;
    }
    
    int test ()
    {
        static counter;
        printf("Total Number of Entries: %d\n", counter);
        return 0;
    }
    
    printfun(x, y, z, a, b, c, d)
    {
        printf("\nAccount Number: %d\n", x);
        printf("Beginning Balance: %.2f\n", y);
        printf("Purchses: %.2f\n", z);
        printf("Payments: %.2f\n", a);
        printf("Credits: %.2f\n", b);
        printf("Interest Accrued: %.2f\n", c);
        printf("Final Ending Balance: %.2f\n\n", d);
    
        return 0;
    }
    }
     
    double purchase()
    {
          double x;
                printf("Purchases: ");
                scanf("%lf", &x);
     
                if(x >= 0)
                      return (x);
                else 
                      return printf("Invalid Entry. Please Try Again\n\n"); purchase();
    }
     
    double payment()
    {
          double x;
                printf("Payments: ");
                scanf("%lf", &x);
     
          if(x >= 0)
                return (x);
          else 
                return printf("Invalid Entry. Please Try Again\n\n"); payment();
     
    }
     
    double credit ()
    { 
          double x;
                printf("Credits/Returns: ");
                scanf("%lf", &x);
     
          return (x);
    }
     
    double iendbal(x, y, z, a)
    {
          return x + y - z - a;
    }
     
    double accint(x)
    {
          return x * .14;
    }
     
    double fendbal(x,y)
    {
          return x + y ;
    }
     
    int test ()
    {
          static counter;
          printf("Total Number of Entries: %d\n", counter);
          return 0;
    }
     
    printfun(x, y, z, a, b, c, d)
    {
          printf("\nAccount Number: %d\n", x);
          printf("Beginning Balance: %.2f\n", y);
          printf("Purchses: %.2f\n", z);
          printf("Payments: %.2f\n", a);
          printf("Credits: %.2f\n", b);
          printf("Interest Accrued: %.2f\n", c);
          printf("Final Ending Balance: %.2f\n\n", d);
     
          return 0;
    }

    Last edited by idfjvafnv; 10-07-2011 at 08:43 AM. Reason: took out pre colored code, also fixed return statements as suggested by commontater

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    First of all what do you think return printf() does? I'm guessing it's not what you think it does...

    Second there's no need for intermediate variables in situations like these...

    Code:
    double iendbal(x, y, z, a)
    {
    double i = x + y - z - a;
    return (i);
    }
    double accint(x)
    {
    double a = x * .14;
    return (a);
    }
    double fendbal(x,y)
    {
    double f = x + y ;
    return (f);
    }
    You can simply do this...

    Code:
    double iendbal(x, y, z, a)
    { 
       return x + y - z - a;
    }
    
    
    double accint(x)
    {
       return x * 0.14;
    }
    
    
    double fendbal(x,y)
    {
      return x + y;
    }
    Finally... don't paste pre-coloured code into the code tags... paste in plain text and the tags will colour it for you.

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by idfjvafnv View Post
    I can't get my spacing to format in the code tags but hopefully it is still readable.
    If you cut n' paste the spaces and tabs should still be there. What did you do to that, BTW? It looks as if you custom highlighted everything, making it very awkward to quote. There is automatic highlighting here. I recommend you edit your post (or, if the new 1 hour limit has been exceeded, re-post) and just use plain text.

    What I need to do is write a series of functions to prompt the user for some input, then I need to return that input to the main then use it in another function to do some calculations then return the calculations back to the main and print the results in another function.
    Maybe you should ask a specific question? Anyway, here is one thing I notice along these lines:

    Code:
    else
    return printf("Invalid Account Number. Please Try Again\n\n"); accno();
    "accno()" will never happen because you have returned from the function.
    Maybe you wanted something like:

    Code:
    else printf("Invalid Account Number. Please Try Again\n\n");
    return accno();
    Returning the printf directly means returning the return value of the printf() function call (which is an integer, the number of bytes printed).
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  4. #4
    Registered User
    Join Date
    Oct 2011
    Posts
    13
    When I wrote return printf() I assumed it would return the text in printf.

  5. #5
    Registered User
    Join Date
    Oct 2011
    Posts
    13
    Quote Originally Posted by MK27 View Post

    Maybe you should ask a specific question? Anyway, here is one thing I notice along these lines:

    Code:
    else
    return printf("Invalid Account Number. Please Try Again\n\n"); accno();
    "accno()" will never happen because you have returned from the function.
    Maybe you wanted something like:

    Code:
    else printf("Invalid Account Number. Please Try Again\n\n");
    return accno();
    Returning the printf directly means returning the return value of the printf() function call (which is an integer, the number of bytes printed).
    these statements work for me and they return the printf statement then prompt me for the function value again.

  6. #6
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by idfjvafnv View Post
    these statements work for me and they return the printf statement then prompt me for the function value again.
    If you mean the code in your original post, you are misinterpreting what is happening, trust me. You need to understand what is really going on or you are going to run into problems quickly.

    Quote Originally Posted by idfjvafnv View Post
    When I wrote return printf() I assumed it would return the text in printf.
    Nope. Here's a tip: you are new to programming, don't work on assumptions. Find out. It is easy to write a short program to test a premise like that one; for one thing, in the process of writing one you might recognize the flaw in your premise:

    Code:
    #include <stdio.h>
    
    int test () {
    /* A function typed "int" returns a single integer */
    	return printf("hello world!\n");
    /* Let's see if something after a return statement will happen */
            test();
    }
    
    int main(void) {
    	int rv = test();
    	/* Now let's see what that integer is */
    	printf("Return value: %d\n", rv);
    
    	return 0;
    }
    Printf() does what it does, and then returns an integer. So of course you see the message printed. But that message is not what was returned (and notice, the "test()" call after the return DOES NOT happen).
    Last edited by MK27; 10-07-2011 at 08:55 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  7. #7
    Registered User
    Join Date
    Oct 2011
    Posts
    13
    I see why your example doesn't work, it would be trying to print rv as an integer and that wouldn't work. But when I return the printf I return the same function right after so that it prints invalid entry. please try again does down 2 lines then reprompts until I get a valid input according to my if statement.

  8. #8
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by idfjvafnv View Post
    I see why your example doesn't work, it would be trying to print rv as an integer and that wouldn't work.
    No, my example does work. Re-read that post. Did you compile it to see the output?

    root~/C»./a.out
    hello world!
    Return value: 13


    So, what this demonstrates is that printf() happens inside the test() function. It is not returned and then printed out. It also demonstrates that stuff like this:

    Code:
               return printf("Invalid Entry. Please Try Again\n\n"); payment();
      
    }
    Is very flawed; payment() will NOT get called. Never. Ever. Not from there. Look:

    Code:
    #include <stdio.h>
    
    void test2() {
    	puts("This function did not get called!");
    }
    
    int test () {
    	printf("hello world!\n");
    	return 5;
    	test2();
    }
    
    int main(void) {
    	test();
    
    	return 0;
    }
    Output:

    root~/C»./a.out
    hello world!
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  9. #9
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by idfjvafnv View Post
    When I wrote return printf() I assumed it would return the text in printf.
    printf() displays text on the screen...
    Look up printf() in your C Library Documentation... see what it does return... almost certainly not what you wanted.

    C functions can only return a single value... so your second return value will either be ignored or cause compiler errors.

  10. #10
    Registered User
    Join Date
    Oct 2011
    Posts
    13
    Ok I'm starting to understand where you're coming from, I'll remove those returns for now and work on them a little later right now I need to focus on getting my values to return correctly and pass to other functions correctly.

  11. #11
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by idfjvafnv View Post
    I see why your example doesn't work, it would be trying to print rv as an integer and that wouldn't work. But when I return the printf I return the same function right after so that it prints invalid entry. please try again does down 2 lines then reprompts until I get a valid input according to my if statement.
    Trust me... it is merely a fluke that it *appears* to work...

  12. #12
    Registered User
    Join Date
    Oct 2011
    Posts
    13
    Ok, I removed the sketchy return statements but I still cannot get my values to return as numbers with 2 decimals any help on where I'm wrong at here.

    Code:
    #include <stdio.h>
    int accno();
    double balance();
    double purchase();
    double payment();
    double credit(); 
    double iendbal();
    double accint();
    double fendbal();
    printfun();
    
    int main ()//main function
    {
    //gather information from functions
    int acc = 0;
    double bal;
    double pur;
    double pay;
    double cr;
    double interest;
    double interim;
    double final;
    int tcust;
    double totfeb;
    static counter = 1;
    acc = accno();
    bal = balance(); 
    pur = purchase();
    pay = payment();
    cr = credit();
    interim = iendbal(bal, pur, pay, cr);
    interest = accint(interim);
    final = fendbal(interest, interim);
    printfun(acc,bal,pur,pay,cr,interest,final);
    
    return 0;
    }
    int accno()
    {
    int x;
    printf("Account Number(between 1000 and 4000 only) - Enter -9999 to Quit: ");
    scanf("%d", &x);
    return (x);
    }
    double balance ()
    {
    double x;
    printf("Beginning Balance: ");
    scanf("%lf", &x);
    return (x);
    }
    double purchase()
    {
    double x;
    printf("Purchases: ");
    scanf("%lf", &x);
    return (x);
    }
    
    double payment()
    {
    double x;
    printf("Payments: ");
    scanf("%lf", &x);
    return (x);
    }
    double credit ()
    { 
    double x;
    printf("Credits/Returns: ");
    scanf("%lf", &x);
    return (x);
    }
    double iendbal(x, y, z, a)
    {
    return x + y - z - a;
    }
    double accint(x)
    {
    return x * .14;
    }
    double fendbal(x,y)
    {
    return x + y ;
    }
    printfun(x, y, z, a, b, c, d)
    {
    printf("\nAccount Number: %d\n", x);
    printf("Beginning Balance: %.2f\n", y);
    printf("Purchses: %.2f\n", z);
    printf("Payments: %.2f\n", a);
    printf("Credits: %.2f\n", b);
    printf("Interest Accrued: %.2f\n", c);
    printf("Final Ending Balance: %.2f\n\n", d);
    return 0;
    }

  13. #13
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Internally doubles will have wild decimal places behind them... because floating point math is only an approximation. There are many values that cannot be exactly represented in floating point format, due to a "last bit ambiguity" problem inherrent in the hardware... 8.00 might become 7.99999999999 and there's not much you can do.

    Most financial programs don't use floating point math, working instead in pennies as integers... For example:
    Code:
    // get penny amount
    int GetAmount(void)
      { double amt;
         printf("Enter amount as dollars and cents : $ ");
         scanf("%lf",&amt)
         return (int)(amt * 100); }  // return pennies.
    
    
    // display pennies as dollars and cents
    void DisplayAmount(int Amt)
      { printf("$ %d.%d",Amt / 100, Amt % 100); }
    The only time the amounts are actually floating point numbers are when asking for inputs.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbie- having trouble with functions
    By bnmwad in forum C Programming
    Replies: 7
    Last Post: 02-22-2005, 04:41 PM
  2. trouble defining member functions
    By dP munky in forum C++ Programming
    Replies: 7
    Last Post: 04-13-2003, 08:52 PM
  3. more trouble with functions
    By volk in forum C++ Programming
    Replies: 3
    Last Post: 03-24-2003, 04:04 AM
  4. trouble with functions
    By volk in forum C++ Programming
    Replies: 9
    Last Post: 03-23-2003, 03:35 PM
  5. trouble with functions with &
    By diaperdandy in forum C++ Programming
    Replies: 4
    Last Post: 12-25-2001, 10:05 PM