# #C Programming(I) - 2 ## Variable type, input and output English: Lei KuoLiang nicolaslouis@mail.fcu.edu.tw Chinese(TW): Wang M.H --- ### This week's course catalog 1. Output methods of variables and variables     * integer int     * floating point number float/double     * character char 2. Variable type variation     * long, short     * sizeof operator     * No number (unsigned), constant (const) 3. Output mode (format specification word) changes 4. stdio.h, input (scanf) --- ## Basic form of C language In the C language, the type is used to store data. We can store this type of "data" by declaring a "variable" of a certain type. ---- ### Variable type Common basic types of C language: int (integer), float (floating point), double (double precision floating point number), char (character), indicator (used to store memory address) ---- ### Declare variables? Let computer ** allocate memory space ** for temporary storage。 ```flow st=>start: variable op=>operation: Memory space st->op-> ``` ```c int a = 5; //Integer float b = 3.14; //Single precision floating point number double c = 3.1415926; //Double precision floating point number char d = 'A'; //Character ``` ---- #### Type table ![](https://i.imgur.com/ujzQS4y.png) --- ### int * integer, integer * In C language, an int variable occupies 4 bytes of memory space, and it can hold values ranging from 2147483647 to -2147483648. ```c= int a = 1; int b = -1; int c = 2147483647; int d = -2147483647; ``` ---- Declare and print an integer ```c= #include <stdio.h> #include <stdlib.h> int main() { int value = 5; //Declare the variable value to int format and assign the value of value to 5 printf("%d\n", value); //%d is a type of format specified word, representing a 10-digit integer return 0; } ``` result ``` 5 ``` ---- #### Format Specifier If you want to specify integers, floating-point numbers, characters, etc. when using printf, you should match the format specification word. Format specified word | Meaning -|- %d|Numbered 10-digit integer(++d++ecimal) %u|No number 10 carry integer %o|No number 8 carry integer(++o++ctal) %x|No lowercase 16-bit integer(he++x++adecimal) %X|No uppercase 16-bit integer ---- ```c= printf("%d\n", 10); // 10 printf("%o\n", 10); // 12 printf("%x\n", 10); // a printf("%X\n", 10); // A ``` ---- Note: Overflow overflow occurs when you output a negative integer using the unsigned integer format (speaking at class) --- ### float / double Floating point number, responsible for storing numbers with decimal points, for example: 3.14, 1.41, -1.0. Name|byte|error -|-|- Float (single-precision floating-point number)|4|accurate to the 7th digit from big to small Double (double precision floating point number) | 8 | accurate to the 15th digit from large to small ---- Declare and print out floating point numbers ```c= #include <stdio.h> #include <stdlib.h> int main() { float pi = 3.14159; //Declare variable pi to float format double root_two = 1.41421; //Declare variable root_two as double format printf("%f\n", pi); //%f stands for single precision floating point format printf("%lf\n", root_two); //%lf stands for double precision floating point format return 0; } ``` result ``` 3.141590 1.414210 ``` ---- #### Format specified word Format specified word | Meaning -|- %f| is expressed as a decimal %e, %E| is represented by a scientific notation (small, uppercase) %g,%G|When the exponent part is in -4 to 5, the output is in decimal format, otherwise the output is in scientific notation format (small, uppercase) * %f, %e, %E, %g, %G are used to represent float * %lf, %le, %lE, %lg, %lG are used to represent double --- ### Exercise 1 Print the information in order according to the requirements of the branch: * 48763 of an integer, expressed in decimal * 48763 of an integer, expressed in octets * Integer 48763, expressed in uppercase hexadecimal * 0.0123 for single-precision floating-point numbers, expressed in decimals * 0.0123 of double-precision floating-point numbers, represented by capitalized scientific notation ``` 48763 137173 BE7B 0.012300 1.230000E-002 ``` --- ### char * character, character * In C language, a char occupies 1 byte of memory space and can store integers ranging from 127 to -128. * Although it is a type of integer, it can store English letters, numbers, and punctuation. (According to the ASCII table, the characters correspond to integers, details will be taught next week) ---- Declare and print characters ```c= #include <stdio.h> #include <stdlib.h> int main() { char capital_a = 'A';//Use a single quotation mark to hold a letter, number, or punctuation to indicate the character printf("%c\n", capital_a); //%c stands for character format printf("%hhd\n", capital_a); //%hhd stands for char integer format return 0; } ``` result ``` A 65 ``` ---- |Bounce character |Description|Bounce character|Description| |-|-|-|-| ==\t== |Horizontal positioning (tab)|\a |Humming ==\n== |Newline|\b |Rewind button ==\\"== |Show double quotes "|\r | Back to the beginning ==\\'== |Show single quotes '|\0 | end of string ==\\\\== |Show backslash \\|==%%== |Show percent sign % --- ## Variable type We have just introduced four basic variable types: int, float, double, char In fact, in addition to the above, there are more variants. ---- **integer** | Type | byte | Range | Output | -------- | -------- |----|-- | char | 1 | -128 ~ 127|%hhd | short int | 2 | -32768 ~ 32767|%hd | int | 4 | approx. ±2.1\*10^9^|%d | long int | 4 | same int|%ld | long long int| 8 | approx. ±9.2\*10^18^|%lld * "int" of short int, long int, long long int can be omitted ---- **Floating point number** |Type | byte | Range (approximately)|Precision|Output method | -------- | -------- |--|-|-- | float | 4 |±3.4\*10^38^|7 digits|%f | double | 8 |±1.8\*10^308^|15 digits|%lf **character** | Type | byte | Range | Output Method | -------- | -------- |--|- | char | 1 |-128 ~ 127|%c ---- ### sizeof `sizeof()`The operator can calculate the memory size (bytes) occupied by the data in `()` ```c= #include <stdio.h> #include <stdlib.h> int main() { printf("size of int: %d\n", sizeof(int)); printf("size of double: %d\n", sizeof(double)); return 0; } ``` Result ``` size of int: 4 size of double: 8 ``` --- ## Advanced type of C language (modifier) unsigned and const Modifier ---- ### unsigned Sometimes we don't need a sign, we can use unsigned to cancel the sign. Unsigned, which is called "no number" in Chinese, is a modifier that turns a numbered form into a no-type. It is usually used to double the maximum value that can be stored in this type, but can only be used in integers. state. ```c //Declare one unsigned long long,And print unsigned long long large_value = 10000000000000000000;//10 to the 19th power printf("%llu\n", large_value); ``` * When the 10-digit unnumbered number is printed, the format designation word %u is used. ---- ### const Constant, constant, refers to a variable that cannot be changed After the variable is declared, it can generally be modified afterwards, but as long as the const modifier is added at the time of the announcement, it becomes a constant that cannot be modified. ```c //Declare a double constant const double PI = 3.14159265358979; ``` --- ### Exercise 2 Print the information in order according to the requirements of the branch: * Declare 3 variables with the char type, assign 70, 67, 85 respectively, and then print the 3 variables in the same line as the character type. * Use the sizeof operator to print the memory size of char, short, int, long, long long in sequence --- ## Format specified word change If you use printf again, you want to set the format, for example: display decimal to number, reserve width, fill 0, left to right, you can add prefix word between % and type of format specified word. ---- ### Common prefix word Prefix word | Description | Example -|-|- | + | Shows the sign of the value. |%+d | (space) | A positive number displays a blank and a negative number displays a -. |% d | (number n) | At least n words, aligned to the right. |%5d | -(number n) | At least n words, aligned to the left. |%-5d | 0 (number n) | At least n words, complement 0. |%05d | . (number n) | Displays n digits after the decimal point when floating point numbers. |%.5f ---- The prefix words in the previous table can be mixed according to the rules in the format: > %[flags][width][.(number)]type * flags can be filled in + or (space) * width can be filled in (number n) or - (number n) or 0 (number n) * type is filled in d, f, lf, c, etc. * flags, width, . (number) can be filled or not filled on request, but type must be filled ---- Demonstration ```c= #include <stdio.h> #include <stdlib.h> int main() { float x = 1.2345678; printf("\"%+-10.5f\"\n", x); //Display positive and negative signs, occupy 10 words, align left, display 5 digits after decimal point (rounded) return 0; } ``` Results of the ``` "+1.23457 " ``` --- ### Exercise 3 According to the topic declaration type, the branches print out specific patterns in sequence: * Type int, assign a value of 123, and print out +123 * Type int, assign a value of 123, and print out 000123 * Type int, assign a value of 123, and print out ""123".    (1 space is reserved behind the number, and the blank key cannot be used, and the double quotation marks are used before and after) * Type double, assign the value 0.01234567, and print out 00.012 ``` +123 000123 "123 " 00.012 ``` --- ## Stdio.h - standard input and output library Stdio.h provides file file operations, input and output (I/O) functions in C language. The printf we used a lot in front of it is one of the functions provided by stdio.h. ---- Here are some standard input and output functions provided by stdio.h: Classification | Function -|- Format I/O|printf(), scanf() ← these 2 most commonly used Character I/O|getchar(), putchar(), puts() --- ## scanf The function opposite printf is scanf, which handles input and is a member of stdio.h. ---- ```c= #include <stdio.h> #include <stdlib.h> int main() { int input; scanf("%d", &input); /* Use the & operator to take the address of the variable, Tell the computer where you want to save it*/ printf("%d\n", input); return 0; } ``` Input ``` 120 ``` Output ``` 120 ``` ---- ### About "&" Unlike printf, when importing parameters, scanf needs to add an & operator to the variable to get the address of the variable. The computer knows which memory address the input value is stored in. ---- scanf() When accepting input, you can specify the "format" of the input.: ![](https://i.imgur.com/g6DNtI2.png) ---- ### About "\n" The first parameter of scanf represents the format entered by the user. Usually, "not too" will add \n to scanf. If you add \n at the end of the format, scanf will wait for the user to enter the next data to complete the input, and scanf will use the data before \n and put the data after \n into the buffer, which will be used as the next input. . ---- ```c= #include <stdio.h> #include <stdlib.h> int main() { int input; scanf("%d\n", &input); //Demonstration join \n, but it is not recommended to write as usual printf("#1 Output %d\n", input); scanf("%d", &input); printf("#2 Output %d\n", input); return 0; } ``` Operation result ``` 12 //Enter 12, line feed, the 7th line of the program is not finished yet. 13 //Enter 13 and line feed. At this point, the 7th line of the program ends. Save 12 to input and put 13 into the buffer. #1 Output 12 //Run the 8th line of the program and output the value in the current input. #2 Output 13 / * Run the program line 9 at this time, because there are 13 in the buffer, directly save 13 into the input               Follow the line 10 of the program*/ ``` ---- ## Format specified word When we use `scanf`, if we want to read the specified integer, floating point number, character, etc., we will also use the "format specification word" such as `%d`, `%f`, `%c`. ---- | type | input | | -------- | -------- | %i|Enter an integer. When reading 8-bit or hexadecimal, start with 0 or 0x or 0X, otherwise it is regarded as 10-bit. | %d|Enter a 10-digit integer. | %o|Enter an 8-digit integer. | %x|Enter a 16-digit integer. | %f|Enter a floating point number. Accept E or e (scientific notation)| %c|Enter the character. | Please note that you may need to add hh, h, l, ll, etc. before type, which means the length of the data type. (Rules with printf) --- ### Exercise 4 Let the user input the following types of variables in sequence and print them out * int * float * double * char ``` Sample input: 123 12.345 34.987 x ``` ``` Sample output: int = 123 float = 12.345000 double = 34.987000 char = 'x' ``` --- ## Homework 1. Save last week's role data using variables 2. Let the user add another character (not named) and display the saved data. ---- Variable declaration example ```c //Character 1 char char1_type = 'W'; int char1_hp = 50; int char1_atk = 15; int char1_def = 5; ``` ---- ``` Role 1 Name: Han Dao Attribute: W Attack: 15 Blood volume: 50 Defense: 5 Role 2 Name: Yasna Attribute: A Attack: 20 Blood volume: 40 Defense: 8 Role 3 Name: Rem Attribute: F Attack: 17 Blood volume: 45 Defense: 7 Added role //This is the input Attribute: F Blood volume: 46 Attack: 18 Defense: 10 Role 4 Name: Custom Role Attribute: F Attack: 18 Blood volume: 46 Defense: 10 ``` --- ## Supplement - Variable naming rules ---- 1. Compiler requirements 2. Engineer self-requirement ---- ### Compiler requirements 1. You can use ABC..., abc..., 0123...9, _ (bottom line) characters, but you can't start with numbers, you can't use Chinese, and the case is different. 2. In the same block, you cannot have two variables with the same name. 3. You cannot use keywords to be a variable name (a word with special meaning in the programming language) ---- C language keyword |||||| -|-|-|-|- auto|short|int|long|float double|char|struct|union|enum typedef|const|unsigned|signed|extern register|static|volatile|void|if else|switch|case|for|do while|goto|continue|break|default sizeof|return ---- ### Engineer self-request (1) 0. Avoid using meaningless variable names, such as: a, b, c, a123, b001, and so on. ---- ### Engineer self-request (2) 1. The variable name should match the stored data. If you need to use more than 2 words, you can use uppercase or bottom line, for example: testScore, test_score. 2. Use all uppercase when declaring constants (const), for example: PI, MAX_SCORE, etc. 3. If you want to use the abbreviation, the general rule can omit the vowel, such as button can be abbreviated as btn, count can be abbreviated as cnt, can also retain the first syllable, such as number can be abbreviated to num. However, please note that after the abbreviation, make sure that others can understand it. --- ## Supplement - printf format specified word ## (advanced version) ---- ### type Earlier we learned a lot of format specified words, such as %d, %c, %f, where the English letters d, c, f are called type or specifier. ---- | type | output | type | output | | -------- | -------- | -------- | -------- | **%d**|10 carry integer|**%u**|no number integer| **%o**|8-bit integer|**%x/%X**|16-integer integer| **%f**|Show floating point numbers in decimals|**%e/%E**|Show floating point numbers with scientific notation| %g/%G| is displayed in decimal or scientific notation |%p| indicator type| **%c**|output in characters |%s|output character array (string)| ---- ### Format specified word change If you use printf again, you want to set the format, for example: display decimal to number, reserve width, fill 0, left to right, you can add prefix word between % and type of format specified word. ---- ### Format specified word syntax >%[flags][width][.precision][length]type ---- #### %==[flags]==[width][.precision][length]type | Flags | Description| | -------- | -------- | | + | Shows the sign of the value. | | (space) | A positive number displays a blank and a negative number displays a -. | | - | Use with width and align left. (default to the right)| | 0 | Use with width, fill 0 in the reserved space. | | # | For %f, %e, %E, the decimal point is always displayed. For %o, %x, %X, the prefix display 0, 0x, 0X indicates the number system. | ---- Demonstration (- with 0 in the width part of the demonstration) ```c= #include <stdio.h> #include <stdlib.h> int main() { printf("%d %d\n", 90, -90); printf("%+d %+d\n", 90, -90); //Positive number + printf("% d % d\n", 90, -90); //Positive number blank key printf("%X %#X\n", 90, 90); //Plus # will indicate the number system return 0; } ``` Results of the ``` 90 -90 +90 -90 90 -90 5A 0X5A ``` ---- #### %[flags]==[width]==[.precision][length]type Width is a positive integer representing the ++ minimum width ++ of the displayed value. Width is often matched with - and 0 in flags. ---- demonstration ```c= #include <stdio.h> #include <stdlib.h> int main() { //Use double quotes to indicate the width range //If the length is greater than or equal to the minimum width, there will be no difference between left and right, and no compensation will be made. printf("\"%5d\" \"%5d\"", 90, 900000); printf("\"%-5d\" \"%-5d\"", 90, 900000); printf("\"%05d\" \"%05d\"", 90, 900000); printf("\"%5s\" \"%-5s\"", "ABC", "ABC"); //%s output character array列 return 0; } ``` Results of the ``` " 90" "900000" "90 " "900000" "00090" "900000" " ABC" "ABC " ``` ---- #### %[flags][width]==[.precision]==[length]type * Precision Chinese is called "accuracy" and is expressed as a decimal point followed by a positive integer. * For floating point values, it represents the number of digits displayed to the right of the decimal point. If necessary, round or zero, the default value is 6. * For integer values, the minimum number of digits, the number of digits that are insufficient will be 0, and the default value is 1. ---- Demonstration ```c= #include <stdio.h> #include <stdlib.h> int main() { float x = 1.2345678; int y = 50; printf("\"%.5f\" \"%.5d\"\n", x, y); //Do not reserve width printf("\"%10.5f\" \"%10.5d\"\n", x, y); //Align right printf("\"%-10.5f\" \"%-10.5d\"\n", x, y); //Align left return 0; } ``` Results of the ``` "1.23457" "00050" " 1.23457" " 00050" "1.23457 " "00050 " ``` ---- #### %[flags][width][.precision]==[length]== type * length represents the length of the data type, and the specified length is given according to the variable type. Length| integer | floating point number |%c| -|-|-|-|-|- Hh |char| h |short| (none)|int|float|char l |long|double| Ll |long long| ---- ### About \* (Advanced Supplement) In the syntax %[flags][width][.precision][length]type, [width] and [.precision] can be filled in with numbers. However, in some cases we want to fill in a variable number, which can be replaced by \*, and the value of the corresponding function parameter represents its value. ---- Demonstration ```c= #include <stdio.h> #include <stdlib.h> int main() { float x = 1.2345678; printf("%10.5f\n", x); printf("%10.*f\n", 5, x); printf("%*.5f\n", 10, x); printf("%*.*f\n", 10, 5, x); return 0; } ``` Results of the ``` 1.23457 1.23457 1.23457 1.23457 ``` --- ###### tags: `108 Ai-Mod-Eng-LKL`
{"metaMigratedAt":"2023-06-15T01:36:53.426Z","metaMigratedFrom":"YAML","title":"W2 - Variable type, input and output","breaks":true,"slideOptions":"{\"transition\":\"slide\"}","contributors":"[{\"id\":\"befaa4d9-75b6-4c05-baa7-7949e0ffa1e2\",\"add\":25171,\"del\":5395}]"}
    246 views