[C++ Programming] Practical combat: C++ data type practice exercises (constants, variables)

Table of contents

1. Constants 

01. Definition of constants: symbolic constants

① Real constant

② Integer constant

③Character constant

02. Definition of constants: named constants

① Integer named constant

② Single precision real named constant

③Character named constants

03. Character constants: scores and rankings

04. Famous constants: price statistics 

05. Famous constant: average score

2. Variables

01. Definition of variables: signed integer variables

① Signed basic integer variable

② Signed short integer variable 

③ Signed long integer variable 

02. Definition of variables: unsigned integer variables

① Unsigned basic integer variable 

② Unsigned short integer variable 

③ Unsigned long integer variable

03. Definition of variables: real variables 

① Single precision real variable 

② Double precision real type variable

04. Definition of variables: character variables

①Character variable

05. Initialization of variables: signed integer variables

① Signed basic integer variable

② Signed short integer variable 

③ Signed long integer variable 

06. Initialization of variables: unsigned integer variables

① Unsigned basic integer variable 

② Unsigned short integer variable 

③ Unsigned long integer variable

07. Initialization of variables: real variables 

① Single precision real variable 

② Double precision real type variable

08. Initialization of variables: character variables

①Character variable

09. Variables: Definition

10. Variables: initialization

11. Variables: parameter passing

12. Variable: format specifier

① Change the placeholder “%d” to the format specifier “%llu”

② Change the placeholder “%d” to the format specifier “%f” or “%e”

13. Variable: Byte count statistics

14. Variable: minimum/maximum value of floating point number float 



1. Constants 

01. Definition of constants: symbolic constants

①Real constant _

#define P1 3.14159    /* 定义符号常量 P1, 其值等于实型常量 3.14159 */

②Integer constant _

#define N 10          /* 定义符号常量 N, 其值等于整型常量 10 */

③Character constants _

#define M 'm'         /* 定义符号常量 M, 其值等于字符常量 m */

02. Definition of constants: named constants

①Integer named constant

const int j=1, k=2;    /* 定义 2 个整型有名常量, j 的值是 1, k 的值是 2 */

②Single precision real named constant

const float f1=3.5, f2=6.8;  /* 定义 2 个单精度实型有名常量,f1 的值是 3.5,f2 的值是 6.8 */

③Character named constants

const char chl='Y', ch2='N';  /* 定义 2 个字符型有名常量,chl 和 ch2 的值分别是字符 Y 和字符 N */

03. Character constants: scores and rankings

【Sample code】 

#include <iostream>

#define CHINESE_SCORE 88 // 宏定义语文成绩的整型常量
#define MATH_SCORE 90.5 // 宏定义数学成绩的实型常量
#define ENGLISH_SCORE 95 // 宏定义英语成绩的整型常量
#define CLASS_RANK "第 19 名" // 宏定义全班排名的字符常量

int main() {
    std::cout << "小茗同学的成绩:" << std::endl;
    std::cout << "语文成绩:" << CHINESE_SCORE << std::endl;
    std::cout << "数学成绩:" << MATH_SCORE << std::endl;
    std::cout << "英语成绩:" << ENGLISH_SCORE << std::endl;
    std::cout << "全班排名:" << CLASS_RANK << std::endl;

    return 0;
}

[Detailed code explanation]

  1. This code is a C++ program that uses macros to define symbolic constants. It is used to output Xiaoming's grades and his ranking in the class.

  2. Use macros to define symbolic constants to define Xiaoming's Chinese, mathematics and English scores as well as the class ranking. "第 19 名" Among them, the class ranking is defined using character constants  .

  3. Use​​​​​​​​​​​​​ in the main function   to outputmain()  Xiaoming’s grades and class ranking.std::cout

【Output result】

小茗同学的成绩:
语文成绩:88
数学成绩:90.5
英语成绩:95
全班排名:第 19 名


04. Famous constants: price statistics 

【Sample code】 

#include <iostream>

int main() {
    const float APPLE_PRICE = 3.5; // 定义常量,单个苹果价格为3.5元
    const int NUM_APPLES = 30; // 定义常量,苹果的数量为30个

    float totalCost = APPLE_PRICE * NUM_APPLES; // 计算总花费

    std::cout << "苹果的价格:" << APPLE_PRICE << " 元" << std::endl;
    std::cout << "苹果的数量:" << NUM_APPLES << " 个" << std::endl;
    std::cout << "总花费:" << totalCost << " 元" << std::endl;

    return 0;
}

[Detailed code explanation]

  1. Two constants are defined, namely  APPLE_PRICE and NUM_APPLES​​​​​​​, whose values ​​are 3.5 and 30 respectively. Use const the ​​​​​​​keyword to indicate that these variables are unmodifiable constants.

  2. A float type totalCost to save the total cost. Its value is equal to the unit price of apples multiplied by the quantity of apples.

  3. Used std::cout to output the results. std::cout For output to the console.

【Output result】

苹果的价格:3.5 元
苹果的数量:30 个
总花费:105 元


05. Famous constant: average score

【Sample code】 

#include <iostream>

int main() {
    const int NUM_STUDENTS = 5; // 定义常量,学生数量为5
    
    // 定义学生的数学分数
    const int mathScores[NUM_STUDENTS] = {13, 24, 57, 80, 90};
    
    int totalScore = 0; // 总分数
    
    // 遍历数组,计算总分数
    for (int i = 0; i < NUM_STUDENTS; ++i) {
        totalScore += mathScores[i];
    }
    
    float averageScore = static_cast<float>(totalScore) / NUM_STUDENTS; // 计算平均分数
    
    std::cout << "学生的数学分数:" << std::endl;
    // 输出学生的数学分数
    for (int i = 0; i < NUM_STUDENTS; ++i) {
        std::cout << "学生" << i + 1 << "的分数:" << mathScores[i] << std::endl;
    }
    
    std::cout << "平均分数:" << averageScore << std::endl;

    return 0;
}

[Detailed code explanation]

  1. A named constant is defined  NUM_STUDENTS, indicating that the number of students is 5.

  2. An integer array is defined  mathScores to store students' math scores, and a curly brace initialization list is used to assign the scores to the array. The size of the array is  NUM_STUDENTS, which ensures that the array can accommodate all students' scores.

  3. An integer variable is defined totalScore to store the total score, with an initial value of 0.

  4. Use a loop to iterate through the array and calculate the total score.

  5. Usestatic_cast<float>(totalScore) ​​​​​​​ to convert the total score to a float, then divide by the number of students NUM_STUDENTSto get the average score.

  6. Use a loop to output each student's math score.

  7. Finally, the average score is output.

【Output result】

学生的数学分数:
学生1的分数:13
学生2的分数:24
学生3的分数:57
学生4的分数:80
学生5的分数:90
平均分数:52.8



2. Variables

01. Definition of variables: signed integer variables

① Signed basic integer variable

int radius, area;     /* 定义 2 个有符号基本整型变量,变量名分别是 radius 和 area */

② Signed short integer variable 

short m, n;           /* 定义 2 个有符号短整型变量,变量名分别是 m 和 n */

③ Signed long integer variable 

long a1, a2;          /* 定义 2 个有符号长整型变量,变量名分别是 a1 和 a2 */

02. Definition of variables: unsigned integer variables

① Unsigned basic integer variable 

unsigned i, j, k;      /* 定义 3 个无符号基本整型变量,变量名分别是 i, j 和 k */
unsigned int x, y;     /* 定义 2 个无符号基本整型变量,变量名分别是 x 和 y */

② Unsigned short integer variable 

unsigned short s1, s2;  /* 定义 2 个无符号短整型变量,变量名分别是 s1 和 s2 */

③ Unsigned long integer variable

unsigned long r;        /* 定义 1 个无符号长整型变量,变量名是 r */

03. Definition of variables: real variables 

①Single  precision real variable 

float radius, area;    /* 定义 2 个单精度实型变量,变量名分别是 radius 和 area*/

②Double  -precision real variable

double fl, f2;         /* 定义 2 个双精度实型变量,变量名分别是 fl 和 f2*/

04. Definition of variables: character variables

①Character variable _

char ch1, ch2;        /* 定义 2 个字符型变量,变量名分别是 ch1 和 ch2 */

05. Initialization of variables: signed integer variables

① Signed basic integer variable

int radius=2, area;    /* 定义 2 个有符号基本整型变量,radius 赋初值为 2, area 无初值 */

② Signed short integer variable 

short m=1, n=2;           /* 定义 2 个有符号短整型变量,m 和 n 分别赋初值为 1 和 2 */

③ Signed long integer variable 

long a1=123R, a2;          /* 定义 2 个有符号长整型变量,a1 赋初值为 123R, a2 无初值 */

06. Initialization of variables: unsigned integer variables

① Unsigned basic integer variable 

unsigned i=1, j, k;      /* 定义 3 个无符号基本整型变量,i 赋初值为 1, j 和 k 无初值 */
unsigned int x, y=0;     /* 定义 2 个无符号基本整型变量,x 无初值,y 赋初值为 0 */

② Unsigned short integer variable 

unsigned short s1=1, s2;  /* 定义 2 个无符号短整型变量,s1 赋初值为 1,s2 无初值 */

③ Unsigned long integer variable

unsigned long r=100;        /* 定义 1 个无符号长整型变量,r 赋初值为 100 */

07. Initialization of variables: real variables 

①Single  precision real variable 

float radius=2.5, area=0.0;  /* 定义 2 个单精度实型变量,radius 赋初值为 2.5, area 赋初值为 0.0 */

②Double  -precision real variable

double fl=1.234, f2=5.6E2;  /* 定义 2 个双精度实型变量,fl 赋初值为 1.234, f2 赋初值为 5.6E2 */

08. Initialization of variables: character variables

①Character variable _

char ch1='Y', ch2='N';        /* 定义 2 个字符型变量,ch1 赋初值为字符 Y,ch2 赋初值为
字符 N */

09. Variables: Definition

Undefined variable, when referencing the variable directly:

  • An error occurred: Undefined identifier "a"
  • Solve the error: define variables first


10. Variables: initialization

When variables are only defined, when variables are not initialized, when variables are referenced: 

  • An error occurred: C6001: Using uninitialized memory "a".
  • Solve the error: When defining a variable, initialize the variable at the same time


11. Variables: parameter passing

When a variable has been defined and initialized, when passing variable parameters: 

  • An error occurred: C6271: Extra parameters passed to "printf"
  • Solve the error: use the placeholder "%d", please note that the parameters passed cannot exceed the number of placeholders in the format string

[Detailed explanation of error reporting]

When calling  printf a function, if more parameters are passed than the number of placeholders in the format string,  C6271 an error will occur. This error refers to  printf the extra parameters passed to:

  • For example, suppose you define an integer variable  num and initialize  10it to , and then want to print it out. The following is a correct example because  "%d" there is a placeholder in  the format string %d to receive  num the value of the integer parameter. The correct code looks like this:
    int num = 10;
    printf("Number: %d\n", num);
    
  • However, if there is only one placeholder in the format string  %d, but multiple parameters are passed to it  printf, an error will be triggered  . In the following code, two parameters  and  C6271 are passed   to  the function, but there is only one  placeholder  in the format string.  Character. This causes the extra parameters to not be processed correctly, causing an error. The error code is as follows:num20printf%d
    int num = 10;
    printf("Number: %d\n", num, 20);
    
  • printf To solve this problem , you need to make sure that the number of arguments passed to  the function matches the number of placeholders in the format string, or that the number of placeholders matches the number of arguments to be printed. For example, if you want to print two integers, you need to use two placeholders  %d,so that  C6271 an error will not be triggered. The correct code is as follows:
    int num1 = 10;
    int num2 = 20;
    printf("Numbers: %d, %d\n", num1, num2);
    


12. Variable: format specifier

① Change the placeholder “%d” to the format specifier “%llu”

When a variable has been defined and initialized, when passing variable parameters: 

  • An error occurred: C6328: Size mismatch: "unsigned _ _int64" was passed as _Param_(2), but "int" was required to call "printf".
  • Resolve the error: To resolve the parameter type mismatch error, modify "%d" to "%llu" and use the  %llu format specifier to  unsigned __int64 match the type, which  llu represents an unsigned long integer.

[Detailed explanation of error reporting]

  • Error C6328 is caused by parameter type mismatch.
  • In the code, a  value of  sizeof(int) a type is returned  , but  is used in the format string passed to the function  , which results in a parameter type mismatch error.unsigned __int64printf%d
  • To solve this problem, you can use  %llu a format specifier to  unsigned __int64 match the type, which  llu represents an unsigned long integer.
  • Here is the corrected code:
    #include <stdio.h>
    
    int main()
    {
    	int a = 0;
    	float b = 0;
    	double c = 0;
    
    	printf("变量名(中文):%d\n", a);
    	printf("变量值(数字):%llu\n" , sizeof(int));
    }
    
  • After the fix, printf the function's parameter types match the format specifier  %llu , so the C6328 error is not triggered.

② Change the placeholder “%d” to the format specifier “%f” or “%e”

When a variable has been defined and initialized, when passing variable parameters: 

  • An error occurs: C6273: When calling "printf" actual type: "double" when an integer is required, non-integer is passed as _Param_(2).
  • Solve the error: To solve the parameter type mismatch error, modify the placeholder "%d" to "%f" or "%e" to print the sum  FLT_MIN .  FLT_MAXThese two values ​​​​are of floating point type, not integer type. You should use  %f or  %e format specifier to print floating point numbers

[Detailed explanation of error reporting]

  • The problem prompted by the error message occurs in the following two lines of code:
    printf("打印浮点数 float 的最小值:%d\n", FLT_MIN);
    printf("打印浮点数 float 的最大值:%d\n", FLT_MAX);
    
  • The cause of the error is that the wrong format specifier is used  %d to print  FLT_MIN and  FLT_MAX, the two values ​​​​are of floating point type, not integer. Floating point numbers should be printed using  %f the or  %e format specifier.
  • The modified code uses  %f an alternative  %d format specifier to print the sum of floating point numbers  FLT_MIN ,  FLT_MAXthus resolving errors in formatted output. The modified code is as follows:
    #include<stdio.h>
    #include <cfloat>
    
    int main()
    {
        int a = 0;                           // 定义并初始化整型变量 a
        float b = 1.5;                       // 定义并初始化浮点型变量 b
        double c = 5.78;                     // 定义并初始化双精度浮点型变量 c
    
        /* 参数传递 */
        printf("打印变量 a 的值:%d\n", a);  // 打印变量 a 的值,使用 %d 格式说明符打印整型值
    
        /* 字节数统计 */
        printf("打印 int 的字节数:%llu\n", sizeof(int));     // 使用 sizeof 运算符获取 int 类型的大小并使用 %llu 格式说明符打印无符号长整型值
        printf("打印 float 的字节数:%llu\n", sizeof(float));   // 使用 sizeof 运算符获取 float 类型的大小并使用 %llu 格式说明符打印无符号长整型值
        printf("打印 double 的字节数:%llu\n", sizeof(double)); // 使用 sizeof 运算符获取 double 类型的大小并使用 %llu 格式说明符打印无符号长整型值
    
        /* 浮点数的最小/大值 */
        printf("打印浮点数 float 的最小值:%f\n", FLT_MIN);
        printf("打印浮点数 float 的最大值:%f\n", FLT_MAX);
    
        return 0;
    }
    


13. Variable: Byte count statistics

【Sample code】 

#include<stdio.h>

int main()
{
    int a = 0;                           // 定义并初始化整型变量 a
    float b = 1.5;                       // 定义并初始化浮点型变量 b
    double c = 5.78;                     // 定义并初始化双精度浮点型变量 c

    /* 参数传递 */
    printf("打印变量 a 的值:%d\n" , a);  // 打印变量 a 的值,使用 %d 格式说明符打印整型值
    
    /* 字节数统计 */
    printf("打印 int 的字节数:%llu\n" , sizeof(int));     // 使用 sizeof 运算符获取 int 类型的大小并使用 %llu 格式说明符打印无符号长整型值
    printf("打印 float 的字节数:%llu\n", sizeof(float));   // 使用 sizeof 运算符获取 float 类型的大小并使用 %llu 格式说明符打印无符号长整型值
    printf("打印 double 的字节数:%llu\n", sizeof(double)); // 使用 sizeof 运算符获取 double 类型的大小并使用 %llu 格式说明符打印无符号长整型值
}

[Detailed code explanation]

  1. Contains a header file  <stdio.h>, which is a standard input and output library file that contains  printf function declarations.
  2. In  main the function, an integer variable is defined  a and initialized to  0, a floating-point variable is defined  b and initialized to  1.5, and a double-precision floating-point variable is defined  c and initialized to  5.78.
  3. The function is used  printf to print  a the value of the variable, int the size of the type, float the size of the type, and the size of the type respectively; the value of the variable and the size of the type are obtained using , , ,  format specifiers and corresponding   operators double respectively  .%d%llu%llu%llusizeof

【Output result】 

  • In most compilers, sizeof(int) the expression returns  int the number of bytes of the type in the current compilation environment.
  • Typically, int a type occupies 4 bytes (32 bits) on most platforms, but this is not guaranteed and may vary on different platforms and compilers.
  • Therefore, when run  , the output is 4, indicating that  the type occupies 4 bytes sizeof(int) in the current compilation environment  .int
  • It should be noted that sizeof the operator returns an unsigned integer value, so when using  %llu the format specifier to print  sizeof(int) the result, you need to use the unsigned long integer ( unsigned long long) format to match the type of the parameter.
打印变量 a 的值:0
打印 int 的字节数:4
打印 float 的字节数:4
打印 double 的字节数:8


14. Variable: minimum/maximum value of floating point number float 

【Sample code】 

#include<stdio.h>
#include <cfloat>

int main()
{
    int a = 0;                           // 定义并初始化整型变量 a
    float b = 1.5;                       // 定义并初始化浮点型变量 b
    double c = 5.78;                     // 定义并初始化双精度浮点型变量 c

    /* 参数传递 */
    printf("打印变量 a 的值:%d\n", a);  // 打印变量 a 的值,使用 %d 格式说明符打印整型值

    /* 字节数统计 */
    printf("打印 int 的字节数:%llu\n", sizeof(int));       // 使用 sizeof 运算符获取 int 类型的大小并使用 %llu 格式说明符打印无符号长整型值
    printf("打印 float 的字节数:%llu\n", sizeof(float));   // 使用 sizeof 运算符获取 float 类型的大小并使用 %llu 格式说明符打印无符号长整型值
    printf("打印 double 的字节数:%llu\n", sizeof(double)); // 使用 sizeof 运算符获取 double 类型的大小并使用 %llu 格式说明符打印无符号长整型值

    /* 浮点数 float 的最小/大值: %f 格式 */
    printf("打印浮点数 float 的最小值:%f\n", FLT_MIN);     // 打印浮点数 float 的最小值,使用 %f 格式说明符打印浮点数值
    printf("打印浮点数 float 的最大值:%f\n", FLT_MAX);     // 打印浮点数 float 的最大值,使用 %f 格式说明符打印浮点数值
    /* 浮点数 float 的最小/大值: %e 格式 */
    printf("打印浮点数 float 的最小值:%e\n", FLT_MIN);     // 打印浮点数 float 的最小值,使用 %e 格式说明符打印浮点数值
    printf("打印浮点数 float 的最大值:%e\n", FLT_MAX);     // 打印浮点数 float 的最大值,使用 %e 格式说明符打印浮点数值
}

[Detailed code explanation]

  1. Contains header files  <stdio.h> and  <cfloat> constants related to input, output and floating point numbers respectively.
  2. In  main the function, an integer variable is defined  a and initialized to  0, a floating-point variable is defined  b and initialized to  1.5, and a double-precision floating-point variable is defined  c and initialized to  5.78.
  3. Use  printf the function to print  a the value of the variable, and use  %d the format specifier to print the integer value.
  4. Functions were used  printf to print  int the type, float type, and  double number of bytes of the type, respectively, and  %llu format specifiers and  sizeof operators were used to obtain and print unsigned long values.
  5. Functions are used  printf to print  float the minimum and maximum values ​​of floating point types respectively, and  %f format specifiers are used to print floating point numbers.
  6. Use  printf the function to print the minimum and maximum values ​​of the floating point type in scientific notation format, respectively  float , and use  %e the format specifier to print the floating point number.

【Output result】 

  • %f Is a format specifier used to print floating point values.
  • %e Is a format specifier used to print the value of a floating point number in scientific notation.
  • Scientific notation: 1.175494e-38 is expressed as 1.175494 times 10 raised to the power of -38
  • Scientific notation: 3.402823e+38 is expressed as 3.402823 times 10 raised to the 38th power
  • 打印变量 a 的值: 0: This is because the variable  a is initialized to the default value of 0 for integers.
  • 打印 int 的字节数: 4: int Type usually occupies 4 bytes (32 bits) of memory space.
  • 打印 float 的字节数: 4: float Type usually occupies 4 bytes (32 bits) of memory space.
  • 打印 double 的字节数: 8: double Types typically occupy 8 bytes (64 bits) of memory space.
  • 打印浮点数 float 的最小值: 0.000000: FLT_MIN is  float the smallest positive non-zero value of the type, usually 0.
  • 打印浮点数 float 的最大值: 340282346638528859811704183484516925440.000000: FLT_MAX is  float the maximum value of the type, usually a very large number.
  • 打印浮点数 float 的最小值: 1.175494e-38float : This is the smallest positive non-zero value of the type expressed in scientific notation  .
  • 打印浮点数 float 的最大值: 3.402823e+38float : This is the maximum value of the type expressed in scientific notation  .
打印变量 a 的值: 0
打印 int 的字节数: 4
打印 float 的字节数: 4
打印 double 的字节数: 8
打印浮点数 float 的最小值: 0.000000
打印浮点数 float 的最大值: 340282346638528859811704183484516925440.000000
打印浮点数 float 的最小值: 1.175494e-38
打印浮点数 float 的最大值: 3.402823e+38

Guess you like

Origin blog.csdn.net/qq_39720249/article/details/131997497