📜  C / C++程序查找int,float,double和char的大小

📅  最后修改于: 2021-05-28 05:16:03             🧑  作者: Mango

给定四种类型的变量,即int,char,float和double,任务是用C或C++编写程序以查找这四种类型的变量的大小。

大小

例子

Input: int
Output: Size of int = 4

Input: double
Output: Size of double = 8

以下是所有数据类型及其大小,范围和访问说明符的列表:

Data Type Memory (bytes) Range Format Specifier
short int 2 -32,768 to 32,767 %hd
unsigned short int 2 0 to 65,535 %hu
unsigned int 4 0 to 4,294,967,295 %u
int 4 -2,147,483,648 to 2,147,483,647 %d
long int 4 -2,147,483,648 to 2,147,483,647 %ld
unsigned long int 4 0 to 4,294,967,295 %lu
long long int 8 -(2^63) to (2^63)-1 %lld
unsigned long long int 8 0 to 18,446,744,073,709,551,615 %llu
signed char 1 -128 to 127 %c
unsigned char 1 0 to 255 %c
float 4 %f
double 8 %lf
long double 12 %Lf

查找四个变量的大小:

  1. 四种类型的变量在integerType,floatType,doubleType和charType中定义
  2. 变量的大小是使用sizeof()运算符计算的。

下面是C和C++程序,用于查找int,char,float和double数据类型的大小:

C
// C program to find the size of int, char,
// float and double data types
  
#include 
  
int main()
{
    int integerType;
    char charType;
    float floatType;
    double doubleType;
  
    // Calculate and Print
    // the size of integer type
    printf("Size of int is: %ld\n",
           sizeof(integerType));
  
    // Calculate and Print
    // the size of charType
    printf("Size of char is: %ld\n",
           sizeof(charType));
  
    // Calculate and Print
    // the size of floatType
    printf("Size of float is: %ld\n",
           sizeof(floatType));
  
    // Calculate and Print
    // the size of doubleType
    printf("Size of double is: %ld\n",
           sizeof(doubleType));
  
    return 0;
}


C++
// C++ program to find the size of int, char,
// float and double data types
#include 
using namespace std;
  
int main() 
{ 
    int integerType; 
    char charType; 
    float floatType; 
    double doubleType; 
  
    // Calculate and Print 
    // the size of integer type 
    cout << "Size of int is: " << 
    sizeof(integerType) <<"\n"; 
  
    // Calculate and Print 
    // the size of doubleType 
    cout << "Size of char is: " << 
    sizeof(charType) <<"\n"; 
      
    // Calculate and Print 
    // the size of charType 
    cout << "Size of float is: " << 
    sizeof(floatType) <<"\n";
  
    // Calculate and Print 
    // the size of floatType 
    cout << "Size of double is: " << 
    sizeof(doubleType) <<"\n"; 
  
    return 0; 
}


输出:
Size of int is: 4
Size of char is: 1
Size of float is: 4
Size of double is: 8
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。