开发者

Data type problems

Can you explain to me why this doesn't work:

#include <iostream>
using namespace std;

double data_conve开发者_JAVA百科rt(int n);

int main(void) {
    cout << data_convert(sizeof(int));
}

double data_convert(int n) {
    int i;
    double x;

    x = 8 * n;
    for(i = 0; i < 32; i++)
        x = x * 32;
    return x;
}

I tried using pow from cmath, but I got the same results. Apparently, this outputs "4.67681e+049". Where as it should output (using Windows Calculator) "4294967296".

The for loop is my own hardcoded pow() function for this specific task. All I wanna do is make a program that can show how big a data type is, along with it's range (bit range or something, yeah?)


If you want 2^32, you should be multiplying by 2 each time. Your code multiplies by 32 each time, so you'll end up with a much larger value.

Also, your x value should start from 1. 8 * n is actually the number of bits in the integer, so that should be your upper limit for the loop:

x = 1;
for (i = 0; i < 8 * n; i++)
  x = x * 2;
return x;

A simpler method would be to bitwise negate 0, which will give you the largest possible integer:

return ~0;

will give you 2^32 - 1 = 4294967295 (on a 32-bit machine).


Basically you are multiplying the input by 8 and are then multiplying that by 32, 32 times.

I don't understand what that is suppose to get you to.

If you want the range of an unsigned integer for x amount of bytes you should use this calculation:

max number = 2^(bytes*8) - 1

So in the loop it should multiply 2 until i goes from 0 to bytes*8 and stop there (So it ends before it gets to bytes*8)


I'm not sure what you're doing, but don't you meanx = x*2?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜