Someone gave me this challenge

See how large a type is by storing powers of 2 in this
list of types: float, double, long double. To determine if a number
will fit, start with 1.0, double it, then divide by 2 to see if you get
the previous number. For example, if a float is 4 bytes then (most likely)
when the value reaches 2^127 and you double and halve it, you will not get
2^127, so 2^128 will not fit, so print the message

2^127 will fit in a float on this platform.
Hint: The exponent to print out (127 in the
example) is just a count of how many times you doubled 1.0.

I'm new at C++ and just keep hitting a mental wall. How would you all do it?

6 Years
Discussion Span
Last Post by nyquist

You could use a while loop with a break statement if the numbers before and after multiplication and division aren't equal. Here is an example for int:

int i = 1,tmp=0,count=0;
	while (true){
		tmp = i;		
		i = i*2;
		i = i / 2;
		if (tmp != i)
		        cout <<"The number n multiplied with 2 can't be saved in 
                                 an integer type:"<<endl;
			cout <<"n = "<<tmp<<" (2^"<<count<<") ---> 2xn = "<<tmp*2;

tmp -> value of i before multiplication and division;
count -> counts how many times i can be multiplied by 2

my results after this code are:
i = 10737741824 = 2^count (count = 30) = 2^30

2^31 would be 2147483648 , but the max number on my system that can be saved in an signed int is 2147483647 so the loop breaks here

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.