C basics: main, printf, and functions · C 基础:main、printf 与函数
C is a compiled language
- C is one of the oldest and most important languages. Linux, databases, and even Python are built with C.
- Unlike Python, C is compiled: the computer first turns your code into a program, then runs it.
- C is strict: every statement ends with a semicolon
;, and every variable needs a type.
C 是一门编译型语言
- C 是最古老、最重要的语言之一。Linux、数据库,甚至 Python 都是用 C 写成的。
- 与 Python 不同,C 是编译型的:计算机先把你的代码变成一个程序,然后再运行它。
- C 很严格:每条语句都以分号
;结尾,每个变量都需要一个类型。
The C skeleton
- Every C program starts in a function called main. Your code goes inside main.
#include <stdio.h>gives youprintf, which prints text.return 0;at the end ofmainmeans "the program finished without an error".
C 的基本骨架
- 每个 C 程序都从一个叫 main 的函数开始。你的代码写在 main 里面。
#include <stdio.h>让你可以使用printf来打印文字。main末尾的return 0;表示“程序没有出错,正常结束”。
#include <stdio.h>
int main(void) {
printf("C runs from inside main.\n");
int year = 11;
printf("Grade %d\n", year);
return 0;
}
printf and types
printfprints text. The\ninside the text means "start a new line".- To print a value, use a placeholder:
%dfor anint,%ffor adouble,%cfor one character. printf("Grade %d\n", year);puts the value ofyearwhere the%dis.- Every variable needs a type first:
int year = 11;ordouble pi = 3.14;.
printf 与类型
printf打印文字。文字里的\n表示“另起一行”。- 要打印一个值,使用占位符:
%d对应int,%f对应double,%c对应单个字符。 printf("Grade %d\n", year);会把year的值放到%d的位置。- 每个变量都要先写类型:
int year = 11;或double pi = 3.14;。
Common mistakes
- Every statement ends with
;, andmainreturnsint(return 0;). printfneeds the right format (%d,%f) and\nfor a new line.
常见错误
- 每条语句以
;结尾,main返回int(return 0;)。 printf要用对格式(%d、%f),换行用\n。
Now you try
- Each task pre-fills the code you need. Write inside
main, or complete the function shown. - Some tasks ask for a function only — do not write your own
main; the checker adds one. - Press Run to compile and run, then Check answer. Your code compiles and runs on the server.
现在轮到你了
- 每个任务都已经预填了需要的代码。在
main里面写代码,或者补全给出的函数。 - 有些任务只要求写一个函数 —— 不要自己写
main,检查器会帮你加上。 - 按 Run(运行) 来编译并运行,然后 Check answer(检查答案)。你的代码在服务器上编译并运行。
Compile then run · 先编译再运行
C source is compiled to a program, which you then run. · C 源代码先被编译成程序,然后才能运行。
Inside · 内部 main, use printf(...) to print exactly Hello, C! on its own line. · 在 main 里面,用 printf(...) 精确地打印 Hello, C!,并单独占一行。
Click Run to see the output here. · 点击“运行”查看此处输出。
Complete the function int square(int n) so it returns n * n. The checker calls it with several values. Do not · 不 write a main — the checker provides one. · 完成函数 int square(int n),让它返回 n * n。检查器会用多个数值来调用它。不要写 main,检查器会提供。
Click Run to see the output here. · 点击“运行”查看此处输出。
Inside · 内部 main, declare int grade = 11;. Then use printf to print two lines: first Hello!, then Grade 11 — print the number with a %d placeholder, not by typing 11. · 在 main 里面,声明 int grade = 11;。然后用 printf 打印两行:第一行 Hello!,第二行 Grade 11 —— 用 %d 占位符打印这个数字,而不是直接打 11。
Click Run to see the output here. · 点击“运行”查看此处输出。