一、C语言基础
cint a; // 整型变量float b; // 浮点型变量char c; // 字符型变量
二、运算符和控制结构
cint sum = a + b; // 算术运算if (a > b) // 关系运算{ printf("a is greater than b\n");}for (int i = 0; i < 10; i++){ printf("%d ", i); // 循环结构}
三、函数
cint add(int x, int y) // 函数定义{ return x + y;}int result = add(a, b); // 函数调用
四、小程序实例
计算两个时间的差值
c#include <stdio.h>struct TIME{ int seconds; int minutes; int hours;};void differenceBetweenTimePeriod(struct TIME t1, struct TIME t2, struct TIME *diff);int main(){ struct TIME startTime, stopTime, diff; printf("输入开始时间: \n"); printf("输入小时、分钟、秒:"); scanf("%d %d %d", &startTime.hours, &startTime.minutes, &startTime.seconds); printf("输入停止时间: \n"); printf("输入小时、分钟、秒: "); scanf("%d %d %d", &stopTime.hours, &stopTime.minutes, &stopTime.seconds); differenceBetweenTimePeriod(startTime, stopTime, &diff); printf("\n差值: %d:%d:%d - ", startTime.hours, startTime.minutes, startTime.seconds); printf("%d:%d:%d ", stopTime.hours, stopTime.minutes, stopTime.seconds); printf("= %d:%d:%d\n", diff.hours, diff.minutes, diff.seconds); return 0;}void differenceBetweenTimePeriod(struct TIME start, struct TIME stop, struct TIME *diff){ if(stop.seconds > start.seconds){ --start.minutes; start.seconds += 60; } diff->seconds = start.seconds - stop.seconds; if(stop.minutes > start.minutes){ --start.hours; start.minutes += 60; } diff->minutes = start.minutes - stop.minutes; diff->hours = start.hours - stop.hours;}
将字符串写入文件
c#include <stdio.h>#include <stdlib.h> /* exit() 函数 */int main(){ char sentence[1000]; FILE *fptr; fptr = fopen("runoob.txt", "w"); if(fptr == NULL) { printf("Error!"); exit(1); } printf("输入字符串:\n"); fgets(sentence, (sizeof sentence / sizeof sentence[0]), stdin); fprintf(fptr,"%s", sentence); fclose(fptr); return 0;}
计算三个整数的排序
c复制#include<stdio.h>void main(){ int x,y,z,t; scanf("%d%d%d",&x,&y,&z); if (x>y) { t=x; x=y; y=t; } if (x>z) { t=x; x=z; z=t; } if (y>z) { t=y; y=z; z=t; } printf("small to big: %d %d %d ",x,y,z);}