C language integer

First, the concept of integer

We are integer data types commonly used in life, is also commonly used as a data programming, C language using the int keyword to define integer variables (int is short for integer).

In the definition of variables, they can add signed, unsigned, short and long four kinds of modifiers.

Signed : signed, it can represent positive and negative numbers.

unsigned : unsigned, can only be a positive number, for example, array indices, such as a person's height.

Short : Short, now under the mainstream 64-bit operating systems, memory for 4-byte integer, using a 4
-byte integer more than enough to save smaller, will idle two bytes, these bytes are wasted a. Early on, or in microcontroller and embedded systems, memory resources are very scarce C language was invented, all programs in memory to save as much as possible.

Long : long, longer integer.

Second, an integer in the range

Integer ranging from computer operating system and C language compiler related, not a fixed value, we can according to its memory size to infer its value range.

A byte has eight bits, represent the range of data it is 2 . 8 -1, i.e., 255.

If the memory is occupied by two bytes, unsigned range is 2 . 8 Ⅹ 2 . 8 -1.

If the amount of memory is four bytes, unsigned range is 2 . 8 Ⅹ 2 . 8 Ⅹ 2 . 8 Ⅹ 2 . 8 -1.

If the amount of memory is eight bytes, unsigned range is 2 . 8 Ⅹ 2 . 8 Ⅹ 2 . 8 Ⅹ 2 . 8 Ⅹ 2 . 8 Ⅹ 2 . 8 Ⅹ 2 . 8 Ⅹ 2 . 8 -1.

If it is signed, the range is halved, because the sign occupy a place.

The following sample code used to test a variety of memory size of an integer.

Example (book60.c)

/*
 * 程序名:book60.c,此程序演示整数占用内存的大小和取值范围。
 * 作者:C语言技术网(www.freecplus.net) 日期:20190525
*/
#include <stdio.h>

int main()
{
  short si;   // 短整数
  int   ii;   // 整数
  long  li;   // 长整数

  printf("sizeof short is %d\n",sizeof(short));
  printf("sizeof int is %d\n",sizeof(int));
  printf("sizeof long is %d\n",sizeof(long));
}

running result

Here Insert Picture Description

sizeof is reserved keywords in C language, an operator, not a function, sizeof actually acquired data storage space in memory occupied, in bytes.

int ii;       // sizeof(int)和sizeof(ii)都可以。

According to the test results book60.c, we can get a variety of ranges of integers.

Type shorthand Type the full name length Ranges
short [signed] short [int] 2 bytes -32768~32767
unsigned short unsigned short [int] 2 bytes 0~65535
int [signed] int 4 bytes -2147483648~2147483647
unsigned int unsigned [int] 4 bytes 0~4294967295
long [signed] long [int] 8 bytes -9223372036854775808~ 9223372036854775807
unsigned long unsigned long [int] 8 bytes 0~18446744073709551615

note:

1) computer with the highest level a symbol to express, unsigned integer does not require a modified sign bit, while expressing a positive integer than the modified signed integer value doubled.

2) when writing a program, the table brackets [] written word can be omitted.

3) When writing the program, to the integer variable assignment can not exceed the range of variables, similar to the following compile time error occurs, the program may also have consequences not run prognosis.

Here Insert Picture Description

4) Now worthless computer's memory, it is recommended programmers less short, caution int, multi-purpose long, memory is not a problem, above all stability program.

Third, the output of the integer

The following table, is important to remember first and second row decimal output format, the past two decades, octal I have never used, hexadecimal number only seen in the display memory addresses, so we do not care and octal hex-related knowledge and understanding can be.

Here Insert Picture Description

Note that a pit: the type of output format control characters correspond best with the type of the variable, otherwise there will be unintended consequences, example:

int i=32767;
printf("i %hd,%d\n",i,i);
int j=32768;
printf("j %hd,%d\n",j,j);

Output:

i 32767,32767
j -32768,32768     // 得到了意外的输出结果,32768超出了short的取值范围。

% Hd for outputting a short integer, the maximum value is 32767, 32767 can be output, but not normal output 32768.

Fourth, write binary, octal and hexadecimal numbers

The default is a decimal digit, represents a decimal number without any special formatting. However, represent a binary, octal or hexadecimal number is not the same, and decimal numbers to distinguish, must be some kind of special wording, specifically, is preceding the number with a particular character, that is, prefix.

1, binary

0 and 1 of two binary digits, must be 0b or 0B (case insensitive) at the beginning of use, for example:

// 以下是合法的二进制
int a = 0b101;      // 换算成十进制为 5
int b = -0b110010;  // 换算成十进制为 -50
int c = 0B100001;   // 换算成十进制为 33
// 以下是非法的二进制
int m = 101010;  // 无前缀 0B,相当于十进制
int n = 0B410;    // 4不是有效的二进制数字

Please note that the standard C language does not support the above binary wording, but some compilers himself was extended only support binary numbers. In other words, not all compilers support binary digits, only part of the compiler support, and a relationship with the version of the compiler.

2, octal

From 0 to 7 octal eight digits, it must begin with 0 (note that 0 is a number, not the letter o) when, for example:

// 以下是合法的八进制数
int a = 015;      // 换算成十进制为 13
int b = -0101;    // 换算成十进制为 -65
int c = 0177777;  // 换算成十进制为 65535

// 以下是非法的八进制
int m = 256;  // 无前缀 0,相当于十进制
int n = 03A2;  // A不是有效的八进制数字

3, hexadecimal

By the hexadecimal digits 0 through 9, letters A ~ F or a ~ f (case insensitive) composition must 0x or 0X (case insensitive) at the beginning of use, for example:

// 以下是合法的十六进制
int a = 0X2A;   // 换算成十进制为 42
int b = -0XA0;  // 换算成十进制为 -160
int c = 0xffff;   // 换算成十进制为 65535

// 以下是非法的十六进制
int m = 5A;    // 没有前缀 0X,是一个无效数字
int n = 0X3H;  // H不是有效的十六进制数字

4, note that the pit

In real life and work, we write decimal numbers, in order to align or other reasons, plus the value 0 in front of it does not matter, but, in the C language, do not add 0 before a decimal number, it will be a computer error considered octal numbers.

Five commonly used library functions

C language provides several commonly used library functions, the following statement:

int  atoi(const char *nptr);  	// 把字符串nptr转换为int整数
long atol(const char *nptr);     // 把字符串nptr转换为long整数
int  abs(const int j);            // 求int整数的绝对值
long labs(const long int j);     // 求long整数的绝对值

Example (book61.c)

/*
 * 程序名:book61.c,此程序演示整数的atoi atol abs labs函数的使用
 * 作者:C语言技术网(www.freecplus.net) 日期:20190525
*/
#include <stdio.h>
#include <stdlib.h>   // 如果不包含这个头文件,会出现意外的结果。

int main()
{
  int  ii;
  long ll;

  ii=atoi("-2147483647");
  ll=atol("-9223372036854775807");
  printf("ii=%d\n",ii);
  printf("ll=%ld\n",ll);

  ii=abs(ii);
  ll=labs(ll);
  printf("ii=%d\n",ii);
  printf("ll=%ld\n",ll);
}

running result

Here Insert Picture Description

Sixth, the data type alias

Typedef C language allows programmers to use keywords to define a data type alias, which generally have two characteristics: 1) a shorter name; 2) more in line with the programmer diet.

For example, from a size_t unsigned int alias.

typedef unsigned int size_t;
size_t ii; 等同于 unsigned int ii;

Let's look at help strlen function, strlen return value is of type size_t.

Here Insert Picture Description

Seven random number

In the actual development, this feature will use a random number, for example, you need to use a random number when writing a program like game.

1 generates a random number

In the C language, we use <stdlib.h> header file srand and rand function to generate a random number.

void srand(unsigned int seed);   // 随机数生成器的初始化函数
int  rand();                        // 获一个取随机数

srand function to initialize the random number generator (commonly known as seeds), in the actual development, we can use the time as a parameter, as long as each different planting time, then the resulting seed is different, final random number is different, usually we use <time.h> header file functions to obtain a precise time to time as the second seed.

Example (book63.c)

/*
 * 程序名:book63.c,此程序用于演示随机数
 * 作者:C语言技术网(www.freecplus.net) 日期:20190525
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
  int ii;

  srand(time(0));  // 播下随机种子

  for (ii=0;ii<5;ii++)  // 生成5个随机数
  {
    printf("%d ", rand());  // 获取随机数
  }

  printf("\n");
}

running result

Here Insert Picture Description

2, a range of random number generation

In the actual development, often needs a random number within a certain range for a certain range of random number generation, it is necessary to use some technique, commonly used method is a modulo operation (take the remainder), plus an adder:

int a = rand() % 50;   // 产生0~49的随机数

If you want to limit the provisions on:

int a = rand() % 51 + 100;   // 产生100~150的随机数

Take the remainder modulo i.e., rand ()% 51 + 100, rand ()% 51 generates a random number is 0 to 50, to ensure a minimum back +100 is only 100, the maximum is 50 + 100 = 150.

Eight, Homework

1) preparation of the sample program, determines the number of bytes short, unsigned short, int, unsigned int, long, unsigned long memory-intensive.

2) multiple-choice questions: Will int values ​​range?

(A) more than two billion (B) -2147483648 ~ 2147483647 © 0 ~ 4294967295

3) multiple-choice questions: Will the long range of values ​​is how much?

(A) many million (B) large enough © -9223372036854775808 ~ 9223372036854775807

4) preparation of the sample program, the numeric string input from the interface, stored in a string variable, and then converted to an integer by atoi function, then output 100 coupled to the screen.

5) In the C language, there is a long int integer is long, you write a program, it takes up memory test and the range of the number of bytes, and long long int type ponder whether they have practical value.

6) the preparation of sample programs, test short, unsigned short, int, unsigned, long, unsigned long assignment beyond the range of consequences.

7) rewrite abs and labs integer library functions to achieve its function, the function declaration as follows:

int   ABS(const int j);                 // 求int整数的绝对值
long LABS(const long int j);           // 求long整数的绝对值

8) using the knowledge already learned, a custom function, the function name is ctoi, the character '0', '1', '2', '3', '4', '5', '6', ' 7 ',' 8 ',' 9 '0,1,2,3,4,5,6,7,8,9 converted to an integer. Function declaration as follows:

int ctoi(const char chr);
chr为用字符方式表示的数字,函数的返回值为数字的整数。

Note: if using or switch statement, chr determination value, and return the results directly.

Call:

printf("'0' is %d\n",ctoi('0'));    // 输出结果是'0' is 0
printf("'9' is %d\n",ctoi('9'));    // 输出结果是'9' is 9

The following job title is difficult, if not complete, do not be too tangled, skill upgrading after the do.

9) a custom function, the function name is knowledge POW, the use of already learned, find a number of n-th power, function declaration as follows:

// 求x的y次幂,函数返回值为x的y次幂。
long  POW(const int x,const int y);

Call:

printf("POW(2,3) is %lu\n",POW(2,3));      // 输出结果是8
printf("POW(10,3) is %lu\n",POW(10,5));    // 输出结果是100000

10) the preparation of the sample program, the number in the string all together, for example, string is "90576483975423", the result is 72 all together.

11) Rewrite integer atoi and atol library functions to achieve its function, the function declaration as follows:

int   ATOI(const char *nptr);  	// 把字符串nptr转换为int整数
long ATOL(const char *nptr);     // 把字符串nptr转换为long整数

Tip: for example the string "12305", 12305 to Integer, open is 2000 + 300 + 10 000 + 0 + 5, i.e., 104 + 1 * 2 * 3 * 103 + 102 + 0 + 5 * 101 * 100

12) fifty-two generates a random number, stored in the array, the range of 1-52, should not be repeated and finally displayed on the screen.

13) the preparation of a poker licensing procedures, the size of a deck of cards in addition to Wang, there are 52 cards, randomly shuffled, and then distributed to four people.

prompt:

(1) The card deck surface may all numerical 1-52, said array is a good choice;

(2) is to generate a range not repeated shuffling of random number between 1-52.

(3) defines an array of four, four representatives, the washing sequence number 52 is assigned to four arrays on the list. If you do not want to define an array of four, with a two-dimensional array is required.

(4) the value of four arrays is displayed, it is that everyone sign face.

Nine, copyright notice

C Language Technology Network original article, reproduced please indicate the source link to the article, the author and original.
Source: C Language Technology Network (www.freecplus.net)
Author: Ethics code Agriculture

If the article typos, or content errors, or other suggestions and comments, please correct me message, thank you very much! ! !

Published an original article · won praise 2 · Views 6728

Guess you like

Origin blog.csdn.net/u010806950/article/details/105044672