Getting Duplicate Lines on printf

Discussion in 'Programmer's Corner' started by beeson76, Feb 21, 2012.

  1. beeson76

    Thread Starter Member

    Apr 19, 2010
    185
    1
    Im working on functions and passing values between functions. Here is a short program I wrote that gives a square root of a number entered (actually the number entered is the square root), but I am not using the sqrt(); function provided in math.h.

    Here is the output:

    Enter a number: (I enter lets say 10)
    Enter a number: (I enter 10 again)

    Then it gives me the answer. Why does it want me to enter a number twice, with the second entry being the one it takes. I am using the Command line of Microsoft Visual Studio Express 2010 as my compiler.

    Code ( (Unknown Language)):
    1.  
    2.  
    3. #include <stdio.h>
    4.  
    5. double square(void);
    6.  
    7. int main(void)
    8. {
    9.     square();   //goes to function square() to computer
    10.    
    11.     printf("Square root of number is %lf", square());
    12.  
    13.     return 0;
    14. }
    15.  
    16.  
    17. double square(void)
    18. {
    19.     double number;
    20.    
    21.     printf("Enter a number: \n");  
    22.     scanf("%lf", &number);
    23.  
    24.     number = number * number;
    25.    
    26.     return number;
    27. }
    28.  
    29.  
    30.  
     
  2. MrChips

    Moderator

    Oct 2, 2009
    12,440
    3,361
    That is because you are calling the function square( ) twice, once in main( ) and again in printf( ) in main( ).
     
  3. beeson76

    Thread Starter Member

    Apr 19, 2010
    185
    1
    Ah Thanks MrChips. I see it now.

    Thanks again.
     
Loading...