初识C语言
第一个程序
#include<stdio.h>
int main(void)
{
printf("Hello World!");
return 0;
}
------------------------------------------------
Hello World!
#include : 预处理器指令
int main(void) : main()总是第一个被调用的函数
每行代码的作用
#include<stdio.h> ←包含另一个文件
int main(void) ←函数名
/* 一个简单的C程序 */ ←注释
{ ←函数体开始
int num; ←声明
printf("I am a simple "); ←调用一个函数
return 0; ←return语句
} ←结束
注释
int main(void)
{
printf("Hello World!");
//这是一行注释printf("Hello World!");
/*这是多行注释printf("Hello World!");
printf("Hello World!");*/
return 0;
}
------------------------------------------------
Hello World!
数据类型
关键字:int 、short、long、unsigned、char、float、double、_Bool、 _Complex、_Imaginary
#include<stdio.h>
int main(void)
{
char name='t';
int age=18;
float a=3.14;
double b=3.1415926;
printf("my name is %c,i am %d\n",name,age);
printf("pi is %f\n",a);
printf("pi is %lf,too\n",b);
return 0;
}
------------------------------------------------
my name is t,i am 18
pi is 3.140000
pi is 3.141593,too
输入和输出
#include<stdio.h>
int main(void)
{
int a;float b;double c;char d;
printf("请输入整数,单精度浮点数,双精度浮点数,字符:\n");
scanf("%d,%f,%lf,%c",&a,&b,&c,&d);
printf("%d,%f,%lf,%c",a,b,c,d);
return 0;
}
------------------------------------------------
请输入整数,单精度浮点数,双精度浮点数,字符:
15,1.5,1.56872268654,j
15,1.500000,1.568723,j
scanf()语句决定了你输入的方式
#include<stdio.h>
int main(void)
{
int a;float b;double c;char d;
printf("请输入整数,单精度浮点数,双精度浮点数,字符:\n");
scanf("%d %f %lf %c",&a,&b,&c,&d);
printf("%d,%f,%lf,%c",a,b,c,d);
return 0;
}
------------------------------------------------
请输入整数,单精度浮点数,双精度浮点数,字符:
1 1.2 5.222555 k
1,1.200000,5.222555,k
使用字符串
#include<stdio.h>
int main(void)
{
char name[10];
printf("please enter your name:\n");
scanf("%s",&name);
printf("your name is %s",name);
return 0;
}
------------------------------------------------
please enter your name:
steve
your name is steve
getchar和putchar
#include<stdio.h>
int main(void)
{
char c;
printf("please enter type of char:");
c=getchar();
printf("\nyou input is:");
putchar(c);
return 0;
}
------------------------------------------------
please enter type of char:k
you input is:k
strlen和sizeof
#include<stdio.h>
int main(void)
{
char str1[10];
int a,b;
printf("please enter str1:\n");
scanf("%s",&str1);
a=strlen(str1);
b=sizeof(str1);
printf("%d,%d",a,b);
return 0;
}
------------------
please enter str1:
abcdefg
7,10
用 strlen()得出的也是字符串中的字符数(包括空格和标 点符号)。然而,sizeof运算符给出的数更大,因为它把字符串末尾不可见 的空字符也计算在内。
预处理
#include<stdio.h>
# define PI 3.14
int main(void)
{
float r,s;
printf("please enter r:\n");
scanf("%f",&r);
s=PI*r*r;
printf("s=%f",s);
return 0;
}
------------------
please enter r:
10
s=314.000000