此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
每个值都有类型
- 在 C 里,每个变量都有一个类型,说明它存放的是哪种值。
- 最常用的三种:
int(整数)、double(带小数点的数)、char(单个字符)。 - 创建变量时必须写出类型:
int n = 5;或double pi = 3.14;。
做算术
- C 用
+、-、*、/做运算,就像计算器一样。 *和/比+和-先算。用小括号( )可以改变顺序。%运算符给出除法的余数:17 % 5是2。
整数的除法不一样
- 两个
int相除时,C 会把小数部分丢掉:7 / 2是3,不是3.5。 - 想保留小数,至少有一边要是
double。7 / 2.0是3.5。 - 你可以使用
(double)将int强制转换为double:(double)sum / count。
读取输入
scanf把输入读进变量。scanf("%d", &n);读入一个int到n。- 注意
n之前的&:scanf需要变量的地址以便填充它。 - 对于需要读取输入的完整程序,Run(运行)首先要求每行输入一个值。Check answer(检查答案)会自动提供测试输入。
English
#include <stdio.h>
int main(void) {
int a = 7, b = 2;
printf("%d\n", a / b); // 3 (integer division)
printf("%.1f\n", a / 2.0); // 3.5 (one side is a double)
printf("%d\n", a % b); // 1 (remainder)
return 0;
}
常见错误
- 声明变量要带类型:
int n;。 - 整数除法向下取整:
7 / 2是3,不是3.5。
现在轮到你
- 整数运算用
/和%;需要小数时用double(或强制转换)。 - 函数任务里,不要自己写
main—— 检查器会提供。 - 对于完整程序,Run(运行)会编译并执行它。对于函数任务,Check answer(检查答案)会使用提供的测试用例编译你的代码并显示结果。
探索
Variables hold a value
A variable is a named box of a fixed type; assigning replaces it.
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
Read one integer n with scanf. A box holds 6 items. Print two lines exactly: Full boxes: then the value of n / 6, and Left over: then the value of n % 6.
点击“运行”查看此处输出。
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
Complete double average3(int a, int b, int c) so it returns the average of the three as a double. Watch out for integer division — divide by 3.0, not 3. Do 不 write a main.
点击“运行”查看此处输出。
难度 1/5 · 今日首次完成可获 100 金币及少量额外奖励
Write double hyp(double a, double b) that returns the hypotenuse length: the square root of a*a + b*b. Use sqrt from <math.h>. Do 不 write a main.
点击“运行”查看此处输出。