I made this code in C++ just to check the biggest integer int and double data types can store.
#include<iostream>
using namespace std;
int main() {
int a, b;
cin >> a;
b = a;
for(int c; a > 1; a = a * b)
cout << a << "\n";
};
When I input 2 in the code below, the biggest integer printed is 1073741824.
I changed the code to:
#include<iostream>
using namespace std;
double main() {
double a, b;
cin >> a;
b = a;
for(double c; a > 1; a = a * b)
cout << a << "\n";
};
The output of the second code quickly from 2 to printing infinity. Why doesn't the code stop at the largest value of double? Why does it stop in the previous code?
The behaviour on overflowing an int is undefined. Because of this it is not possible to elucidate the maximum possible value that can be stored in an int. So we have to rely on a constant that your platform will provide for you: std::numeric_limits<int>::max() is the value of the largest int.
For the double case, technically the behaviour is also undefined. Although if your platform implements IEEE754, then +Inf will eventually be attained by repeated multiplication of a large enough value; a little over 11. The largest double that isn't +Inf that your platform supports is std::numeric_limits<double>::max().
Finally, main is not allowed to return anything other than an int. Didn't your compiler warn you of that?
1 The actual value of "a little" is std::numeric<double>::epsilon(). Acknowledge @YSC.
I made this code in C++ just to check the biggest integer int and double data types can store
This is how you get the largest value you can store in a data type:
#include <iostream>
#include <limits>
using namespace std; // not in real code plz
int main() {
cout << "largest int is " << numeric_limits<int>::max() << '\n';
cout << "largest double is " << numeric_limits<double>::max() << '\n';
return 0;
}
Your trial multiplication wouldn't get this right even if it was well-defined: it would just show you the last value of a such that the real maximum is between a and a*b.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With