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?

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;
			break;
		}
		i=i*2;
		count++;
	}

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.