Thread: Average of integers with 2 accurate decimals

  1. #1
    Registered User
    Join Date
    May 2019
    Posts
    2

    Average of integers with 2 accurate decimals

    Hello,

    Thank you for looking at my issue.

    I am wondering why my decimals are always .00 even if they are supposed to be .50 or something etc. Next is the code and a screenshot of the program in action.

    Code:
    #include <stdio.h>
    
    
    main()
    {
        int first_number, second_number;
        float average;
    
    
        printf("Enter the first number:");
        scanf("%d", &first_number);
    
    
        printf("Enter the second number: ");
        scanf("%d", &second_number);
    
    
        average = ( first_number + second_number ) / 2;
    
    
        printf("\naverage is %.2f", average);
    
    
        return 0;
        }
    Attached Images Attached Images Average of integers with 2 accurate decimals-capture-jpg Average of integers with 2 accurate decimals-capture2-jpg 

  2. #2
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    Because you are evaluating an integer expression: 1/2 (with integers) is 0
    Change to:
    Code:
    average = ( first_number + second_number ) / 2.0f;
    This 2.0f, at the end, will promote the first subexpression to float before the division is made.

  3. #3
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    An warning:

    There is the matter of precision to consider... int has 31 bits of precision, but float has 24. This means, if you enter 17777777 twice you won't get 17777777 as average:
    Code:
    $  cat test.c
    #include <stdio.h>
    
    int main( void )
    {
      int a, b;
    
      scanf("%d %d", &a, &b );
      printf( "%.2f\n", ( a + b ) / 2.0f );
    }
    
    $ ./test <<< '17777777 17777777'
    17777776.00
    In this context, you should change the type to double, which has 53 bits of precision (the constant 2.0f need to loose this 'f' at the end).

    PS: If you aren't using any functions from "math.h", you don't need to include the header file.
    Last edited by flp1969; 05-04-2019 at 01:52 PM.

  4. #4
    Registered User
    Join Date
    May 2019
    Posts
    2
    Thank you ! excellent, thanks for the warning also!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 27
    Last Post: 02-14-2015, 11:17 AM
  2. HW Help - Average & Total of six integers
    By Pl2lNCE in forum C Programming
    Replies: 2
    Last Post: 01-23-2013, 12:10 PM
  3. Integers Sums & Average Through Function
    By snayyer in forum C Programming
    Replies: 1
    Last Post: 03-09-2011, 06:01 AM
  4. New to C++: Decimals to Integers?
    By MyntiFresh in forum C++ Programming
    Replies: 18
    Last Post: 06-29-2005, 05:37 AM
  5. Replies: 4
    Last Post: 03-03-2003, 03:52 PM

Tags for this Thread