📜  C++中带符号char的最大值

📅  最后修改于: 2021-05-30 11:27:09             🧑  作者: Mango

在本文中,我们将讨论C++中的签名char数据类型。

带符号的char数据类型的某些属性是:

  • 它通常用于存储8位字符。
  • 作为有符号数据类型,它可以存储正值和负值。
  • 占用8位大小,其中1位用于存储值的符号。
  • 可以以带符号的char数据类型存储的最大值通常为127,约为2 7 – 1 (但取决于编译器)。
  • 可以存储在带符号的char中的最大值和最小值作为常量存储在climits头文件中,并且可以分别命名为SCHAR _ MAX和SCHAR_MIN
  • 可以存储在带符号的char数据类型中的最小值通常为-128, 大约– 2 7 (但取决于编译器)。
  • 如果数据类型上溢或下溢,则将值包装起来。例如,如果将-128存储为带符号的char数据类型,并从中减去1,则该变量中的值将等于127。类似地,在发生溢出的情况下,该值将四舍五入为-128

以下是获取最高值的程序,该程序可以在C++中存储在带符号的char中:

C++
// C++ program to obtain the maximum value
// that we can store in signed char
#include 
#include 
using namespace std;
  
// Driver Code
int main()
{
  
    // From the constant of climits
    // header file
    signed char valueFromLimits = SCHAR_MAX;
    cout << "Maximum value from "
         << "climits constant: "
         << (int)valueFromLimits
         << '\n';
  
    valueFromLimits = SCHAR_MIN;
    cout << "Minimum value from "
         << "climits constant: "
         << (int)valueFromLimits
         << '\n';
  
    // Using the wrap around property
    // of data types
  
    // Initialize two variables one
    // value with -1 as previous and
    // one with 0 as present
    signed char previous = -1;
    signed char present = 0;
  
    // Keep on increasing both values
    // until the present increases to
    // the max limit and wraps around to
    // the negative value i.e., present
    // becomes less the previous value
    while (present > previous) {
        previous++;
        present++;
    }
  
    cout << "Maximum value using the "
         << "wrap around property: "
         << (int)previous << '\n';
  
    cout << "Maximum value using the "
         << "wrap around property: "
         << (int)present;
  
    return 0;
}


输出:
Maximum value from climits constant: 127
Minimum value from climits constant: -128
Maximum value using the wrap around property: 127
Maximum value using the wrap around property: -128
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”