1

The problem is that my program does not give accurate average for numbers with more than 9 digits.

Can somebody point out what am I doing wrong and how do I fix that? Is there anything I can do to improve the code any further?

The code is

#include <iostream>
using namespace std;

int main(){
    cout << "                 Average Finder           \n";  //So that the title is displayed properly.
    int NUM1,NUM2,AVG;  /*I am defining the variables as integers, seemed like the best option.
                          Should I use long float? Does that even work?*/ 
    cout << "Type the First Number:   "; // for the display
    cin >> NUM1; // the program asks for the first user input and stores it in integer variable NUM1
    cout << " \n";
    cout << "Type the Second Number:  ";
    cin >> NUM2;  // the program asks for the second user input and stores it in integer variable NUM2
    cout << " \n";
    AVG = ((NUM1+NUM2)/2); //this line calculates their average
    cout << "The Average of given numbers is = ";
    cout << AVG;
    
    return 0;
}

Here is the command line executions.

PS D:\Workspace\Coding\C++> .\ALG001.EXE

                 Average Finder
Type the First Number:   1111111111

Type the Second Number:  1111111111

The Average of given numbers is = -1036372537
JaMiT
  • 14,422
  • 4
  • 15
  • 31
  • Have you [considered](https://stackoverflow.com/questions/1855459/maximum-value-of-int) what is the [maximum value](https://stackoverflow.com/a/589684/1563833) you can store in a variable of type `int`? – Wyck Jul 02 '21 at 05:16

2 Answers2

2

Your NUM1 and NUM2 are of type int. int variables have a maximum value, on most systems it is 2147483647.

When NUM1 = 1111111111 and NUM2 = 1111111111, then NUM1 + NUM2 will be bigger than the the maximum value 2147483647. This is called overflow.

Technically in c++ this is undefined behaviour, but on most systems it will wrap around giving you negative values and explaining your output.

If you want your variables to store larger values, use long or even long long.

SomeProgrammer
  • 1,134
  • 1
  • 6
  • 12
  • And when int64_t is too small, you can use gmpxx.h and its type mpz_class. Items of this type are a multiprecision integer. – 2785528 Jul 01 '21 at 21:42
  • So, The user input exceeded the maximum limit, Like a cup being over-filled. Thus resulting in an Overflow. And the solution was to simply increase the volume of cup. Did I get that right? – StumblingBlock001 Jul 19 '21 at 19:00
  • Yes, although (technically) the sum of your two numbers exceeded the maximum limit, not the user input. – SomeProgrammer Jul 23 '21 at 15:02
0

You'll want to use floating point for the average. And beware of integer division:

double average = 0.0;
average = (1 + 2 + 3) / 3.0;
std::cout << average << "\n";

With integer division, 1 / 3 == 0.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154