Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ช่วงข้อมูลของชนิดข้อมูลและแมโครใน C++

งานคือการหาช่วงหน่วยความจำของชนิดข้อมูลต่างๆ ว่าชนิดข้อมูลแต่ละชนิดเก็บค่าได้ตั้งแต่ค่าต่ำสุดถึงค่าสูงสุด มีช่วงหน่วยความจำที่กำหนดไว้ การจดจำช่วงค่าขนาดใหญ่ยาก ดังนั้น C++ มีแมโคร (macros) แทนตัวเลขใหญ่เหล่านี้ สามารถกำหนดให้ตัวแปรโดยตรงโดยไม่ต้องพิมพ์ช่วงตัวเลขทั้งหมด

ตัวอย่าง

char (signed) เป็น character data type มีช่วง -128 ถึง +127 แมโครสำหรับค่าต่ำสุดและสูงสุดคือ CHAR_MIN และ CHAR_MAX

เช่นเดียวกัน สำหรับ int ใช้ INT_MIN และ INT_MAX

ช่วงของ char

-128 ถึง +127

ช่วงของ int

-2,147,483,648 ถึง +2,147,483,647

ตัวอย่างโค้ด

#include <iostream>
#include <climits>
#include <cfloat>
using namespace std;

int main() {
    cout << "Range of Char : " << CHAR_MIN << " to " << CHAR_MAX;
    cout << "\nRange of int : " << INT_MIN << " to " << INT_MAX;
    cout << "\nRange of float : " << FLT_MIN << " to " << FLT_MAX;
    cout << "\nRange of double : " << DBL_MIN << " to " << DBL_MAX;
    cout << "\nRange of signed char : " << SCHAR_MIN << " to " << SCHAR_MAX;
    cout << "\nRange of unsigned char : " << 0 << " to " << UCHAR_MAX;
    cout << "\nRange of long int : " << LONG_MIN << " to " << LONG_MAX;
    cout << "\nRange of unsigned int : " << 0 << " to " << UINT_MAX;
    cout << "\nRange of short int : " << SHRT_MIN << " to " << SHRT_MAX;
    cout << "\nRange of float negative : " << -FLT_MIN << " to " << -FLT_MAX;
    cout << "\nRange of double negative: " << -DBL_MIN << " to " << -DBL_MAX;
    return 0;
}

เอาต์พุต (ตัวอย่าง)

Range of Char : -128 to 127
Range of int : -2147483648 to 2147483647
Range of float : 1.17549e-38 to 3.40282e+38
Range of double : 2.22507e-308 to 1.79769e+308
Range of signed char : -128 to 127
Range of unsigned char : 0 to 255
Range of long int : -9223372036854775808 to 9223372036854775807
Range of unsigned int : 0 to 4294967295
Range of short int : -32768 to 32767
Range of float negative : -1.17549e-38 to -3.40282e+38
Range of double negative : -2.22507e-308 to -1.79769e+308

หมายเหตุ

  • ใช้ header <climits> สำหรับ integer limits และ <cfloat> สำหรับ floating-point limits
  • ค่าที่แท้จริงอาจแตกต่างไปตามแพลตฟอร์มและคอมไพเลอร์
  • ใน C++11 ขึ้นไป แนะนำให้ใช้ std::numeric_limits<T>::min() และ ::max() แทน