确定带符号和无符号数据类型C ++范围的公式 [英] Formula to determine the range of signed and unsigned data types C++

查看:60
本文介绍了确定带符号和无符号数据类型C ++范围的公式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是刚开始使用C ++(实际上是第二天),我被分配来计算各种数据类型(带符号和无符号)的范围.问题是,我学校的工作方式使我无法继续学习数学部分,他在这里再教我们几个月的公式.他说要从已经完成数学课程的人那里获得信息,但是所有人都说他们将在有笔记的家里进行这项工作.因此,现在我对Google及其不确定的答案一无所知,所以我问您,stackoverflow的明智之手.

I'm just starting out in C++ (literally my second day) and I've been assigned to calculate the ranges of the varying data types, signed and unsigned. The problem is, the way my school works I won't get to the Math portion where he teaches us the formula for another couple months. He said to get the information from someone who has done the math course already however all of them said they're going to work on this from home where they have their notes. So now I'm left in the dark with google and its inconclusive answers, so I ask you, the wise folk of stackoverflow.

获取数据类型范围的公式是什么?我为INT找到了一个有效但不适用于另一个的变量,他希望我们计算的变量为:char,short,long和long long.他还希望这4和INT的无符号版本.

What are the formulas for getting the range of the data types? I have found one for INT that has worked but does not apply to the others, the ones he wants us to calculate are: char, short, long, and long long. He also wants the unsigned versions of those 4 as well as INT.

我们已经具有每种数据类型的大小(以位和字节为单位).

We already have the size in bits and bytes of each of these data types.

这是我布置INT范围的方式:

Here is how I have my INT range laid out:

    printf ("\nThe range of int is: %f\n", pow(2, (sizeof(int) * CHAR_BIT) -1));

推荐答案

std :: numeric_limits< T>

您可以使用以下功能获取这些限制的实际值:

std::numeric_limits<T>

You can get the actual values of these limits using these functions:

您用适当的类型代替 T ,例如 signed char unsigned char .

You substitute the appropriate type in place of T, such as signed char or unsigned char.

具有N位的带符号数字的公式(使用二进制补码)

The formulas for a signed number with N bits (using two's complement) are

  • min = -1 * 2 N-1
  • max = 2 N-1 -1

N位无符号数字的公式为

The formulas for an unsigned number with N bits are

  • min = 0
  • max = 2 N -1

char 具有N = 8位.让我们用 signed char unsigned char 验证这些公式.

The char has N = 8 bits. Let's verify these formulas with signed char and unsigned char.

  • 签名字符
    • min = -1 * 2 N-1 = -1 * 2 7 = -128
    • max = 2 N-1 -1 = 2 7 -1 = 127
    • signed char
      • min = -1 * 2N - 1 = -1 * 27 = -128
      • max = 2N - 1 - 1 = 27 - 1 = 127
      • min = 0
      • max = 2 N -1 = 2 8 -1 = 255
      • min = 0
      • max = 2N - 1 = 28 - 1 = 255

      这篇关于确定带符号和无符号数据类型C ++范围的公式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆