Galang Kangin
Galang Kangin

Reputation: 1

c++: a program to find the average of very high numbers?

so im trying to make a c++ program that can find the average of very high numbers (the range was <10^19)

heres my attemp:

#include <iostream>
int main()
{

    long double a,b,result;
    std::cin>>a;
    std::cin>>b;
    result=(a+b)/2;
    std::cout<<result<<"\n";
}

but somehow i did not the result i expected. my teacher said there was a "trick" and there was no need to even use double. but i search and researched and did not found the trick. so any help?

Upvotes: 0

Views: 118

Answers (1)

Matthieu M.
Matthieu M.

Reputation: 300059

When using floating point numbers you have to consider their precision, it is represented by std::numeric_limits<T>::digits10 in base 10, and the following program can give them (they may depend on your platform):

#include <iostream>
#include <limits>

int main() {
    std::cout << "float: " << std::numeric_limits<float>::digits10 << "\n";
    std::cout << "double: " << std::numeric_limits<double>::digits10 << "\n";
    std::cout << "long double: " << std::numeric_limits<long double>::digits10 << "\n";
    return 0;
}

On ideone I get:

float: 6
double: 15
long double: 18

Which is consistent with 32 bits, 64 bits and 80 bits floating point numbers (respectively).

Since 1019 is above 18 digits (it has 20), the type you have chosen lacks the necessary precision to represent all numbers below it, and no amount of computation can recover the lost data.


Let's switch back to integrals, while their range is more limited, they have a higher degree of precision for the same amount of bits. A 64 bits signed integer has a maximum of 9,223,372,036,854,775,807 and the unsigned version goes up to 18,446,744,073,709,551,615. For comparison 1019 is 10,000,000,000,000,000,000.

A uint64_t (from <cstdint>) gives you to necessary building block, however you'll be teetering on the edge of overflow: 2 times 1019 is too much.

You now have to find a way to compute the average without adding the two number together.

Supposing two integers M, N such that M <= N, (M + N) / 2 = M + (N - M) / 2

Upvotes: 2

Related Questions