1、say hello
#include <stdio.h>
main()
{
printf("Say Hello\n");
}
#include <stdio.h>可以调用标准I/O的函数。例如printf、scanf等
2、fahr celsius转换
华氏温度转换摄氏温度的demo.
公式:摄氏度 = (5/9)(华氏度-32)
while循环
#include <stdio.h>
main()
{
int f,c;
int lower,upper,step;
lower = 0;
upper = 200;
f = 0;
step = 20;
while (f <= upper){
c = 5*(f-32)/9;
printf ("%d\t%d\n",f,c);
f = f + step;
}
}
for循环
#include<stdio.h>
main()
{
for(int f=0;f<=200;f=f+20)
{
printf("%d\t%d\n",f,5*(f-32)/9);
}
}
3、符号常量
#define指令可以把符号名定义为一个特定的字符串
#include <stdio.h>
#define LOWER 0
#define UPPER 200
#define STEP 20
main()
{
int f;
for (f=LOWER;f<=UPPER;f=f+STEP)
{
printf("%d\t%d\n",f,5*(f-32)/9);
}
}
4、字符输入和输出
getchar和putchar
#include <stdio.h>
main()
{
int c;
while((c=getchar())!=EOF)
{
putchar(c);
}
}
EOF end of file.
5、函数
#include<stdio.h>
int power(int m, int n);
main()
{
int i;
for (i=0;i < 10; ++i)
printf("%d %d %d\n",i,power(2,i),power(-3,i));
return 0;
}
int power(int base, int n)
{
int i,p;
p=1;
for (i=1;i<=n;++i)
{
p=p*base;
}
return p;
}
奇怪,为什么要在上面声明power,否则会警告?
power.c:7:25: warning: implicit declaration of function 'power' is invalid in C99
[-Wimplicit-function-declaration]
int power(int m, int n);
这种声明称为函数原型,它必须与power函数的定义和用法一致。
6、字符数组
#define MAXLINE 1000
int getline(char line[], int maxline);
void copy(char to[], char from[]);
main(){
int len;
int max;
char line[MAXLINE];
char longest[MAXLINE];
max = 0;
while ((len = getline(line, MAXLINE)) > 0)
if (len > max){
max = len;
copy(longest, line);
}
if (max > 0)
printf("%s", longest);
return 0;
}
int getline(char s[], int lim)
{
int c, i;
for (i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
s[i] = c;
if (c == '\n'){
s[i] = c;
++i;
}
s[i]='\0';
return i;
}
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}
getline.c:3:5: error: conflicting types for 'get line'
int getline(char s[], int maxline);
^
/usr/include/stdio.h:449:9: note: previous declaration is here
ssize_t getline(char ** __restrict, size_t * __restrict, FILE * __restrict)
嘿,这是为什么呢?
if (c == '\n'){
s[i] = c;
++i;
}
s[i]='\0';
getline函数把字符'\n'插入到它创建的数组的末尾,用来标记字符串的结束。这一约定已被c语言采用,类似“hello\n”的字符串常量时,它将以字符串数组的形式存储,数组的个元素分别存储字符串的各个字符,并以'\0'的标志字符串的结束。
Others:
#include <stdio.h>
#include <stdlib.h>
main(){
int i,j,temp;
int min;
int s[5];
for (i=0;i<5;++i)
{
s[i]=rand()%100;
printf("%d\n",s[i]);
}
for (i=0;i<4;i++)
{
min=i;
for(j=i+1;j<5;j++){
if (s[j]<s[i])
min=j;
}
if (min!=i){
temp = s[i];
s[i] = s[min];
s[min] = temp;
}
}
for (i=0;i<5;i++)
{
printf("%d\n",s[i]);
}
}