Reputation: 13
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
Upvotes: 1
Views: 74
Reputation: 57698
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
.
Upvotes: 0
Reputation: 1294
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
.
Upvotes: 2