【C语言第一章基本概念】

基本概念

输入输出

输入

C supports a number of ways for taking user input.
getchar() Returns the value of the next single character input.

#include <stdio.h>

int main() {
    char a = getchar();

    printf("You entered: %c", a);

    return 0;
}

The input is stored in the variable a.

The gets() function is used to read input as an ordered sequence of characters, also called a string.
A string is stored in a char array.

#include <stdio.h>

int main() {
    char a[100];

    gets(a); 

    printf("You entered: %s", a);

    return 0;
}

Here we stored the input in an array of 100 characters.

scanf() scans input that matches format specifiers.
The “f” stands for “formatted”.

#include <stdio.h>

int main() {
    int a;
    scanf("%d", &a);

    printf("You entered: %d", a);

    return 0;
}

The & sign before the variable name is the address operator. It gives the address, or location in memory, of a variable. This is needed because scanf places an input value at a variable address

As another example, let’s prompt for two integer inputs and output their sum:

#include <stdio.h>

int main() {
    int a, b;
    printf("Enter two numbers:");
    scanf("%d %d", &a, &b);

    printf("\nSum: %d", a+b);

    return 0;
}

scanf() stops reading as soon as it encounters a space, so text such as “Hello World” is two separate inputs for scanf().

输出

putchar() Outputs a single character.

#include <stdio.h>

int main() {
  char a = getchar();

  printf("You entered: ");
  putchar(a);

  return 0;
}

The puts() function is used to display output as a string.

#include <stdio.h>

int main() {
  char a[100];

  gets(a); 

  printf("You entered: ");
  puts(a); 

  return 0;
} 

Formatted Input

The scanf() function is used to assign input to variables. A call to this function scans input according to format specifiers that convert input as necessary.
If input can’t be converted, then the assignment isn’t made.
The scanf() statement waits for input and then makes assignments:

#include <stdio.h>

int main() {
    int x;
    float num;
    char text[20];
    scanf("%d %f %s", &x, &num, text);
}

Typing 10 22.5 abcd and then pressing Enter assigns 10 to x, 22.5 to num, and abcd to text.
Note that the & must be used to access the variable addresses. The & isn’t needed for a string because a string name acts as a pointer.

Format specifiers begin with a percent sign % and are used to assign values to corresponding arguments after the control string. Blanks, tabs, and newlines are ignored.
A format specifier can include several options along with a conversion character:

%[*][max_field]conversion character

The optional * will skip the input field.
The optional max_width gives the maximum number of characters to assign to an input field.
The conversion character converts the argument, if necessary, to the indicated type:
d decimal
c character
s string
f float
x hexadecimal

#include <stdio.h>

int main() {
    int x, y;
    char text[20];

    scanf("%2d %d %*f %5s", &x, &y, text);
    /* input: 1234  5.7  elephant */
    printf("%d  %d  %s", x, y, text);
    /* output: 12  34  eleph */

    return 0;
} 

Formatting Output

The printf function was introduced in your very first Hello World program. A call to this function requires a format string which can include escape sequences for outputting special characters and format specifiers that are replaced by values.
printf_s(); could be used instead of printf(); it is a more secure version

#include <stdio.h>

int main() {
    printf("The tree has %d apples.\n", 22);
    /* output: The tree has 22 apples. */

    printf("\"Hello World!\"\n");
    /* output: "Hello World!" */
}

Escape sequences begin with a **backslash **:
\n new line
\t horizontal tab
\ backslash
\b backspace
single quote
" double quote

Format specifiers begin with a percent sign % and are replaced by corresponding arguments after the format string. A format specifier can include several options along with a conversion character:

%[-][width].[precision]conversion character

The optional - specifies left alignment of the data in the string.
The optional width gives the minimum number of characters for the data.
The period . separates the width from the precision.
The optional precision gives the number of decimal places for numeric data. If s is used as the conversion character, then precision determines the number of characters to print.
The conversion character converts the argument, if necessary, to the indicated type:
d decimal
c character
s string
f float
e scientific notation
x hexadecimal

#include <stdio.h>

int main() {
    printf("Color: %s, Number: %d, float: %5.2f \n", "red", 42, 3.14159);
    /* Color: red, Number: 42, float:  3.14  */

    printf("Pi = %3.2f \n", 3.14159); 
    /* Pi = 3.14 */
    
    printf("Pi = %8.5f \n", 3.14159); 
    /* Pi = 3.14159 */
    
    printf("Pi = %-8.5f \n", 3.14159); 
    /* Pi = 3.14159 */
    
    printf("There are %d %s in the tree. \n", 22, "apples");
    /* There are 22 apples in the tree. */
}

To print the % symbol, use %% in the format string.

注释

Comments are explanatory information that you can include in a program to benefit the reader of your code. The compiler ignores comments, so they have no affect on a program.
A comment starts with a slash asterisk /* and ends with an asterisk slash */ and can be anywhere in your code.
Comments can be on the same line as a statement, or they can span several lines.
Comments clarify the program’s intent to the reader. Use comments to clarify the purpose and logic behind segments of code.

Single-line Comments

C++ introduced a double slash comment // as a way to comment single lines. Some C compilers also support this comment style.
Adding comments to your code is good programming practice. It facilitates a clear understanding of the code for you and for others who read it.

运算符

Arithmetic Operators

C supports arithmetic operators + (addition), - (subtraction), * (multiplication), / (division), and % (modulus division).
Operators are often used to form a numeric expression such as 10 + 5, which in this case contains two operands and the addition operator.
Numeric expressions are often used in assignment statements.
C has two division operators: / and %.
The division / operator performs differently depending on the data types of the operands. When both operands are int data types, integer division, also called truncated division, removes any remainder(余数) to result in an integer. When one or both operands are real numbers (float or double), the result is a real number.
The % operator returns only the remainder of integer division. It is useful for many algorithms, including retrieving digits from a number. Modulus division cannot be performed on floats or doubles.

#include <stdio.h>

int main() {
    int i1 = 10;
    int i2 = 3;
    int quotient, remainder;
    float f1 = 4.2;
    float f2 = 2.5;
    float result;

    quotient = i1 / i2;  // 3
    remainder = i1 % i2;  // 1
    result = f1 / f2;  // 1.68

    printf("%d \n", quotient);
    printf("%d \n", remainder);
    printf("%f \n", result);

    return 0;
}

Operator Precedence(优先级)

C evaluates a numeric expression based on operator precedence.
The + and – are equal in precedence, as are , /, and %.
The , /, and % are performed first in order from left to right and then + and -, also in order from left to right.
You can change the order of operations by using parentheses ( ) to indicate which operations are to be performed first.
For example, the result of 5 + 3 * 2 is 11, where the result of (5 + 3) * 2 is 16.
C may not evaluate a numeric expression as desired when the associative property allows any order. For example, x
y
z may be evaluated as (x * y) * z or as x * (y * z). If order is important, break the expression into separate statements.

Type Conversion

When a numeric expression contains operands of different data types, they are automatically converted as necessary in a process called type conversion.
For example, in an operation involving both floats and ints, the compiler will convert the int values to float values.
In the following program, the increase variable is automatically converted to a float:

#include <stdio.h>

int main() {
    float price = 6.50;
    int increase = 2;
    float new_price;

    new_price = price + increase;
    printf("New price is %4.2f", new_price);
    /* Output: New price is 8.50 */

    return 0;
}

Note the format specifier includes 4.2 to indicate the float is to be printed in a space at least 4 characters wide with 2 decimal places.
When you want to force the result of an expression to a different type you can perform explicit type conversion by type casting, as in the statements:

#include <stdio.h>

int main() {
    float average;
    int total = 23;
    int count = 4;

    average = (float) total / count;
    
    printf("%4.2f", average);

     return 0;
}

Without the type casting(类型转换), average will be assigned 5.
Explicit type conversion(显示类型转换), even when the compiler may do automatic type conversion(自动类型转换), is considered good programming style.

Assignment Operators

An assignment statement evaluates the expression on the right side of the equal sign first and then assigns that value to the variable on the left side of the =. This makes it possible to use the same variable on both sides of an assignment statement, which is frequently done in programming.

int x = 3;
x = x + 1;  /* x is now 4 */

Increment & Decrement(递增和递减)

Adding 1 to a variable can be done with the increment operator ++. Similarly, the decrement operator – is used to subtract 1 from a variable.

z--;  /* decrement z by 1 */
y++; /* increment y by 1 */

The increment and decrement operators can be used either prefix (before the variable name) or postfix (after the variable name). Which way you use the operator can be important in an assignment statement, as in the following example.

#include <stdio.h>

int main() {
    int x, y, z;
    
    z = 3;
    x = z--;  /* assign 3 to x, then decrement z to 2 */
    printf("x=%d \n", x);
    
    y = 3;
    x = ++y;  /* increment y to 4, then assign 4 to x */
    
    printf("x=%d \n", x);
    
    printf("y=%d \n", y);

    return 0;
}

The prefix form increments/decrements the variable and then uses it in the assignment statement.
The postfix form uses the value of the variable first, before incrementing/decrementing it.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值