Hello World!
#include<stdio.h>
int main() {
printf("Hello World!");
return 0;
}
结果:
Hello World!
#include预处理指令,包含一个头文件
stdio 就是指 “standard input & output"(标准的输入输出)
#include<stdio.h>包含“stdio.h”头文件,stdio.h头文件包含了scanf()(输入)和printf()(输出)等函数。
定义main主函数,返回值的类型为int(整型类型),程序从主函数开始运行。
类型
int 整型,整数类型,范围为-231 — 231-1 (-2,147,483,648 到 2,147,483,647) 如int a=1;
long long 长整型,大小是int的4倍(范围更大) 如long long a=1;
float/double 单/双精度浮点型,小数 如double a=1.5;(一般常用double类型)(double比float精度高,花费的代价小,一般直接使用double,double yyds)
char 字符类型 如char c=‘a’;
字符串类型(char数组) 如char s[]=“Hello World!”;
数组
int a[5],b[5]={0,1,2,3,4},c[]={5,6,7,8,9};
定义一个长度为5个int类型的数组a
定义一个长度为5个int类型的数组b,并进行初始化
定义一个数组c,初始化,长度为5
ps:数组下标从0开始。
int a[5]={1,2,3,4,5};
for (int i=0; i <= 5; ++i) {
printf("%d ",&a[i]);
}
输出
1 2 3 4 5
输入输出函数
printf()函数(输出函数)
int a=12,b=21;
printf("a = %d,b = %d",a,b);
结果:
a = 12,b = 21
按照“”内的原模原样输出,“”后的是变量
用%d(整型)来输出整型变量a和b的内容
scanf()函数(输入函数)
int a,b;
scanf("%d b=%d",&a,&b);
printf("a = %d,b = %d",a,b);
输入:
12 b=21
结果:
a = 12,b = 21
按照“”内的原模原样输入,&去地址符,“”后面变量的地址
用%d(整型)来输入,输入内容到整型变量a,b内;
常见的控制类型:
%d int(整型)
%lld long long(长整型)
%lf double(双精度浮点型)
%c char(字符类型)
%s string(字符串类型)
条件
if条件
if (condition1) {
statements1
}
else if (condition2) {
statements2
}
else statements3
如果condition1成立,则执行statements1,否则判断condition2
如果condition2成立,则执行statements2
否则执行statements3
循环
for循环
for (initialization; condition; increment) {
statements //循环主体
}
初始化:initialization会首先被执行,且只会执行一次。声明并初始化任何循环控制变量。
条件:判断 condition。如果为真,则执行循环主体。如果为假,结束for循环。
更新:在执行完 for 循环主体后,执行上面的 increment 语句。更新循环控制变量。
int n=10;
for (int i=1; i <= n; ++i) {
printf("%d ",i);
}
输出
1 2 3 4 5 6 7 8 9 10
while循环
while (condition) {
statements
}
满足condition时,执行statements。
int n=10,i=1;
while(i <= n) {
printf("%d ",&i);
i++;
}
输出
1 2 3 4 5 6 7 8 9 10