C语言入门例子集合
标签(空格分隔): c 编程 练习
//系统预处理引入
#include<stdio.h>
#include<math.h>
#include <limits.h>
#include <float.h>
#include <string.h>
//自定义预处理引入
#include "stdafx.h"
//预处理定义常量
#define PI 3.1415926
#define NEWLINE ' '
//const关键字定义常量
const int MAX_BYTE = 255;
// 变量声明
//extern 跨文件声明变量
extern int z3;
extern float z4;
//变量定义
double a;
//变量初始化
a=4;
//变量定义并初始化
int b = 3;
// 函数声明
int func();
// 函数定义
int func()
{
return 0;
}
void printHelloWorld() {
printf("hello world. \n");
}
void getCharFromNum() {
int num;
printf("请输入一个数字\n");
scanf("%d", &num);
printf("你输入了数字:%d\n", num);
printf("转换为ANSCII字符为:%c\n", num);
}
void getInterest() {
double rate = 0.03;
double money = 6000, interest;
int term = 4;
printf("money:");
scanf("%lf", &money);
printf("term:");
scanf("%d", &term);
interest = money*pow((rate + 1), term) - money;
printf("money:%.1lf,term:%d,interest:%.2lf\n", money, term, interest);
}
//-------------------
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
void printBooksInfo() {
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy(Book1.title, "C Programming");
strcpy(Book1.author, "Nuha Ali");
strcpy(Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy(Book2.title, "Telecom Billing");
strcpy(Book2.author, "Zara Ali");
strcpy(Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info */
printf("Book 1 title : %s \n", Book1.title);
printf("Book 1 author : %s \n", Book1.author);
printf("Book 1 subject : %s \n", Book1.subject);
printf("Book 1 book_id : %d \n", Book1.book_id);
/* print Book2 info */
printf("Book 2 title : %s \n", Book2.title);
printf("Book 2 author : %s \n", Book2.author);
printf("Book 2 subject : %s \n", Book2.subject);
printf("Book 2 book_id : %d \n", Book2.book_id);
}
//-------------------
void printDataTypeSize() {
printf("Storage size for int : %d \n", sizeof(int));
printf("Storage size for float : %d \n", sizeof(float));
printf("Minimum float positive value: %E \n", FLT_MIN);
printf("Maximum float positive value: %E \n", FLT_MAX);
printf("Precision value: %d", FLT_DIG);
}
/*
假设,如果A = 60;且b = 13;现在以二进制格式它们将如下:
A = 0011 1100
B = 0000 1101
---------------- -
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
A << 2 1111 0000
A >> 2 0000 1111
*/
//----------------------
/* 函数定义 */
int max(int num1, int num2);
int main()
{
/* 局部变量定义 */
int a = 100;
int b = 200;
int ret;
/* 调用函数返回最大值 */
ret = max(a, b);
printf("最大值是 : %d", ret);
return 0;
}
/* 函数返回两数之间最大值 */
int max(int num1, int num2)
{
//return num1 > num2 ? num1 : num2;
/* 局部变量定义 */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
//----------------------------
//数组定义
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
balance[4] = 50.0;
double salary = balance[9];
void printArray() {
int n[10]; /* n is an array of 10 integers */
int i, j;
/* initialize elements of array n to 0 */
for (i = 0; i < 10; i++)
{
n[i] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 10; j++)
{
printf("Element[%d] = %d\n", j, n[j] );
}
}
//指针
void printPointerAddress() {
int var1;
char var2[10];
printf("Address of var1 variable: %x\n", &var1);
printf("Address of var2 variable: %x\n", &var2);
}
int *ip; /* yiibaier to an integer */
double *dp; /* yiibaier to a double */
float *fp; /* yiibaier to a float */
char *ch /* yiibaier to a character */
void printPointerValue() {
int var = 20; /* actual variable declaration */
int *ip; /* yiibaier variable declaration */
ip = &var; /* store address of var in yiibaier variable*/
printf("Address of var variable: %x\n", &var);
/* address stored in yiibaier variable */
printf("Address stored in ip variable: %x\n", ip);
/* access the value using the yiibaier */
printf("Value of *ip variable: %d\n", *ip);
}
void printAddress() {
int *a = NULL;
int b = 4;
a = &b + 1;
printf("The value of ptr is : %x\n", b);
printf("The value of ptr is : %x\n", &b);
printf("The value of ptr is : %x\n", *a);
getchar();
}
//----------------------------
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books book );
void printBook( struct Books book )
{
printf( "Book title : %s", book.title);
printf( "Book author : %s", book.author);
printf( "Book subject : %s", book.subject);
printf( "Book book_id : %d", book.book_id);
}
int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Nuha Ali");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Zara Ali");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info */
printBook( Book1 );
/* Print Book2 info */
printBook( Book2 );
return 0;
}
//---------------------------
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook(struct Books book);
Books setBook(char title[], char author[], char subject[], int bookId);
void printBook(struct Books book)
{
printf("Book title : %s\n", book.title);
printf("Book author : %s\n", book.author);
printf("Book subject : %s\n", book.subject);
printf("Book book_id : %d\n", book.book_id);
}
Books setBook(char title[], char author[], char subject[], int bookId)
{
struct Books book;
strcpy(book.title, title);
strcpy(book.author, author);
strcpy(book.subject, subject);
book.book_id = bookId;
return book;
}
int main()
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
Book1 = setBook("C Programming", "Nuha Ali", "C Programming Tutorial", 6495407);
/* book 2 specification */
Book2 = setBook("Telecom Billing", "Zara Ali", "Telecom Billing Tutorial", 6495700);
/* print Book1 info */
printBook(Book1);
/* Print Book2 info */
printBook(Book2);
return 0;
}
void printCalcOperator(){
int a = 21;
int b = 10;
int c=0;
printf("Line 0:a,b,c的初始值值是 a=%d,b=%d,c=%d\n", a,b,c);
c = a + b;
printf("Line 1:c = a + b,c 的值是 %d\n", c);
c = a - b;
printf("Line 2:c = a - b,c 的值是 %d\n", c);
c = a * b;
printf("Line 3:c = a * b,c 的值是 %d\n", c);
c = a / b;
printf("Line 4:c = a / b,c 的值是 %d\n", c);
c = a % b;
printf("Line 5:c = a %% b,c 的值是 %d\n", c);
c = a++;
printf("Line 6:c = a++,c 的值是 %d\n", c);
a = 21;
c = a--;
printf("Line 7:c = a--,c 的值是 %d\n", c);
}
void printSetValueOperator(){
int a = 21;
int c;
c = a;
printf("Line 1 - = 运算符实例,c 的值 = %d\n", c);
c += a;
printf("Line 2 - += 运算符实例,c 的值 = %d\n", c);
c -= a;
printf("Line 3 - -= 运算符实例,c 的值 = %d\n", c);
c *= a;
printf("Line 4 - *= 运算符实例,c 的值 = %d\n", c);
c /= a;
printf("Line 5 - /= 运算符实例,c 的值 = %d\n", c);
c = 200;
c %= a;
printf("Line 6 - %= 运算符实例,c 的值 = %d\n", c);
c <<= 2;
printf("Line 7 - <<= 运算符实例,c 的值 = %d\n", c);
c >>= 2;
printf("Line 8 - >>= 运算符实例,c 的值 = %d\n", c);
c &= 2;
printf("Line 9 - &= 运算符实例,c 的值 = %d\n", c);
c ^= 2;
printf("Line 10 - ^= 运算符实例,c 的值 = %d\n", c);
c |= 2;
printf("Line 11 - |= 运算符实例,c 的值 = %d\n", c);
}
void printOthers(){
int a = 4;
short b;
double c;
int* ptr;
/* sizeof 运算符实例 */
printf("Line 1 - 变量 a 的大小 = %d\n", sizeof(a) );
printf("Line 2 - 变量 b 的大小 = %d\n", sizeof(b) );
printf("Line 3 - 变量 c 的大小 = %d\n", sizeof(c) );
/* & 和 * 运算符实例 */
ptr = &a; /* 'ptr' 现在包含 'a' 的地址 */
printf("a 的值是 %d\n", a);
printf("*ptr 是 %d\n", *ptr);
/* 三元运算符实例 */
a = 10;
b = (a == 1) ? 20: 30;
printf( "b 的值是 %d\n", b );
b = (a == 10) ? 20: 30;
printf( "b 的值是 %d\n", b );
}
//结构,位域,指针
main(){
struct bs{
unsigned a:1;
unsigned b:3;
unsigned c:4;
} bit,*pbit;
bit.a=1; /* 给位域赋值(应注意赋值不能超过该位域的允许范围) */
bit.b=7; /* 给位域赋值(应注意赋值不能超过该位域的允许范围) */
bit.c=15; /* 给位域赋值(应注意赋值不能超过该位域的允许范围) */
printf("%d,%d,%d\n",bit.a,bit.b,bit.c); /* 以整型量格式输出三个域的内容 */
pbit=&bit; /* 把位域变量 bit 的地址送给指针变量 pbit */
pbit->a=0; /* 用指针方式给位域 a 重新赋值,赋为 0 */
pbit->b&=3; /* 使用了复合的位运算符 "&=",相当于:pbit->b=pbit->b&3,位域 b 中原有值为 7,与 3 作按位与运算的结果为 3(111&011=011,十进制值为 3) */
pbit->c|=1; /* 使用了复合位运算符"|=",相当于:pbit->c=pbit->c|1,其结果为 15 */
printf("%d,%d,%d\n",pbit->a,pbit->b,pbit->c); /* 用指针方式输出了这三个域的值 */
}
//共用体 一样可以使用指针
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}
//结构
#include <stdio.h>
#include <string.h>
struct
{
unsigned int age : 3;
} Age;
int main( )
{
Age.age = 4;
printf( "Sizeof( Age ) : %d\n", sizeof(Age) );
printf( "Age.age : %d\n", Age.age );
Age.age = 7;
printf( "Age.age : %d\n", Age.age );
Age.age = 8;
printf( "Age.age : %d\n", Age.age );
return 0;
}
//位域
#include <stdio.h>
#include <string.h>
/* 定义简单的结构 */
struct
{
unsigned int widthValidated;
unsigned int heightValidated;
} status1;
/* 定义位域结构 */
struct
{
unsigned int widthValidated : 1;
unsigned int heightValidated : 31;
} status2;
int main()
{
printf("Memory size occupied by status1 : %d\n", sizeof(status1));
printf("Memory size occupied by status2 : %d\n", sizeof(status2));
return 0;
}
#include <stdio.h>
#include <string.h>
struct
{
unsigned int age : 3;//3位最大存储7
} Age;
int main()
{
Age.age = 4;
printf("Sizeof( Age ) : %d\n", sizeof(Age));
printf("Age.age : %d\n", Age.age);
Age.age = 7;
printf("Age.age : %d\n", Age.age);
Age.age = 8;
printf("Age.age : %d\n", Age.age);
return 0;
}
//typedef
#include <stdio.h>
#include <string.h>
typedef struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} Book;
int main( )
{
Book book;
//如果struct没有用typedef定义,上面的book声明会是如下形式
//struct Book book;
strcpy( book.title, "C Programming");
strcpy( book.author, "Nuha Ali");
strcpy( book.subject, "C Programming Tutorial");
book.book_id = 6495407;
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
return 0;
}
//int getchar(void) 函数从屏幕读取下一个可用的字符,并把它返回为一个整数。这个函数在同一个时间内只会读取一个单一的字符。您可以在循环内使用这个方法,以便从屏幕上读取多个字符。
//int putchar(int c) 函数把字符输出到屏幕上,并返回相同的字符。这个函数在同一个时间内只会输出一个单一的字符。您可以在循环内使用这个方法,以便在屏幕上输出多个字符。
#include <stdio.h>
#include <string.h>
//getchar & putchar 获取/输出单个字符
int main()
{
int c = 0;
while (c != 'e')
{
printf("\nEnter a value :");
c = getchar();
printf("\nYou entered: ");
putchar(c);
printf("\n");
}
return 0;
}
//获取输出字符数组
#include <stdio.h>
int main()
{
char str[100];
printf("Enter a value :");
gets(str);//gets = getStr的缩写
printf("\nYou entered: ");
puts(str);
return 0;
}
#include <stdio.h>
int main( ) {
char str[100];
int i;
printf( "Enter a value :");
scanf("%s %d", str, &i);
printf( "\nYou entered: %s %d ", str, i);
printf("\n");
return 0;
}
//文件操作
FILE *fopen( const char * filename, const char * mode );//打开
int fclose( FILE *fp );//关闭
int fputc( int c, FILE *fp );//写入字符
int fputs( const char *s, FILE *fp );//写入字符串
int fprintf(FILE *fp,const char *format, ...) //写入字符串
int fgetc( FILE * fp );//读取字符,返回值是读取的字符,如果发生错误则返回 EOF。
char *fgets( char *buf, int n, FILE *fp );//读取字符串
int fscanf(FILE *fp, const char *format, ...) //读取字符串
二进制 I/O 函数
下面两个函数用于二进制输入和输出:
size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);
size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements, FILE *a_file);
//这两个函数都是用于存储块的读写 - 通常是数组或结构体。
//打开创建文件,写入内容
#include <stdio.h>
main()
{
FILE *fp;
//fp = fopen("D:\\test.txt", "w+");//这是windows系统的文件路径格式
fp = fopen("/tmp/test.txt", "w+");//这是linux系统上的文件路径格式
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}
//读取内容
#include <stdio.h>
int main()
{
FILE *fp;
char buff[255];
fp = fopen("test.txt", "r");
fscanf(fp, "%s", buff);
printf("1 : %s\n", buff);
fgets(buff, 255, (FILE*)fp);
printf("2: %s\n", buff);
fgets(buff, 255, (FILE*)fp);
printf("3: %s\n", buff);
fclose(fp);
}
//预处理器指令
#define MAX_ARRAY_LENGTH 20
#include <stdio.h>
#undef FILE_SIZE
#define FILE_SIZE 42
#ifndef MESSAGE
#define MESSAGE "You wish!"
#endif
#ifdef DEBUG
/* Your debugging statements here */
#endif
#include <stdio.h>
int main()
{
printf("File :%s\n", __FILE__);
printf("Date :%s\n", __DATE__);
printf("Time :%s\n", __TIME__);
printf("Line :%d\n", __LINE__);
//printf("ANSI :%d\n", __STDC__);
}
//宏
//宏延续运算符(\)
//字符串常量化运算符(#)
//标记粘贴运算符(##)
#include <stdio.h>
#define message_for(a, b) \
printf(#a " and " #b ": We love you!\n")
int main(void)
{
message_for(Carole, Debra);
return 0;
}
#include <stdio.h>
#define tokenpaster(n) printf ("token" #n " = %d", token##n)
int main(void)
{
int token34 = 40;
tokenpaster(34);
return 0;
}
#include <stdio.h>
#if !defined (MESSAGE)
#define MESSAGE "You wish!"
#endif
int main(void)
{
printf("Here is the message: %s\n", MESSAGE);
return 0;
}
//函数
int square(int x) {
return x * x;
}
//转换为宏
#define square(x) ((x) * (x))
#include <stdio.h>
#define MAX(x,y) ((x) > (y) ? (x) : (y))
int main(void)
{
printf("Max between 20 and 10 is %d\n", MAX(10, 20));
return 0;
}
//头文件
//有两种类型的头文件:程序员编写的头文件和编译器自带的头文件。
#include <file>//这种形式用于引用系统头文件。
#include "file"//这种形式用于引用用户头文件。
//只引用一次头文件
#ifndef HEADER_FILE
#define HEADER_FILE
the entire header file file
#endif
//有条件引用
#if SYSTEM_1
# include "system_1.h"
#elif SYSTEM_2
# include "system_2.h"
#elif SYSTEM_3
...
#endif
//错误码
//大多数的 C 或 UNIX 函数调用返回 1 或 NULL,同时会设置一个错误代码 errno,该错误代码是全局变量,表示在函数调用期间发生了错误。您可以在 <error.h> 头文件中找到各种各样的错误代码。
//perror() 函数显示您传给它的字符串,后跟一个冒号、一个空格和当前 errno 值的文本表示形式。
//strerror() 函数,返回一个指针,指针指向当前 errno 值的文本表示形式。
#include <stdio.h>
#include <errno.h>
#include <string.h>
extern int errno ;
int main ()
{
FILE * pf;
int errnum;
pf = fopen ("unexist.txt", "rb");
if (pf == NULL)
{
errnum = errno;
fprintf(stderr, "错误号: %d\n", errno);
perror("通过 perror 输出错误");
fprintf(stderr, "打开文件错误: %s\n", strerror( errnum ));
}
else
{
fclose (pf);
}
return 0;
}
//被零除的错误
#include <stdio.h>
#include <stdlib.h>
main()
{
int dividend = 20;
int divisor = 0;
int quotient;
if( divisor == 0){
fprintf(stderr, "除数为 0 退出运行...\n");
exit(-1);
}
quotient = dividend / divisor;
fprintf(stderr, "quotient 变量的值为 : %d\n", quotient );
exit(0);
}
//程序退出状态
//通常情况下,程序成功执行完一个操作正常退出的时候会带有值 EXIT_SUCCESS。在这里,EXIT_SUCCESS 是宏,它被定义为 0。
//如果程序中存在一种错误情况,当您退出程序时,会带有状态值 EXIT_FAILURE,被定义为 -1。所以,上面的程序可以写成:
#include <stdio.h>
#include <stdlib.h>
main()
{
int dividend = 20;
int divisor = 5;
int quotient;
if( divisor == 0){
fprintf(stderr, "除数为 0 退出运行...\n");
exit(EXIT_FAILURE);
}
quotient = dividend / divisor;
fprintf(stderr, "quotient 变量的值为: %d\n", quotient );
exit(EXIT_SUCCESS);
}
//数的阶乘
//下面的实例使用递归函数计算一个给定的数的阶乘:
#include <stdio.h>
double factorial(unsigned int i)
{
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1);
}
int main()
{
int i = 15;
printf("%d 的阶乘为 %f\n", i, factorial(i));
return 0;
}
//斐波那契数列
//下面的实例使用递归函数生成一个给定的数的斐波那契数列:
#include <stdio.h>
int fibonaci(int i)
{
if(i == 0)
{
return 0;
}
if(i == 1)
{
return 1;
}
return fibonaci(i-1) + fibonaci(i-2);
}
int main()
{
int i;
for (i = 0; i < 10; i++)
{
printf("%d\t\n", fibonaci(i));
}
return 0;
}
//斐波那契
int main()
{
int a = 0, b = 1,c=0;
for (int i = 0; i < 50; i++)
{
printf("%d\n", a);
c = a + b;
a = b;
b = c;
}
return 0;
}
位运算符 | p | q | p&q | p\ | q | p^q |
---|---|---|---|---|---|---|
0 | 0 | 0 | 0 | 0 | ||
0 | 1 | 0 | 1 | 1 | ||
1 | 1 | 1 | 1 | 0 | ||
1 | 0 | 0 | 1 | 1 |
typedef vs #define
#define 是 C 指令,用于为各种数据类型定义别名,与 typedef 类似,但是它们有以下几点不同:
- typedef 仅限于为类型定义符号名称,#define不仅可以为类型定义别名,也能为数值定义别名,比如您可以定义 1 为 ONE。
- typedef 是由编译器执行解释的,#define 语句是由预编译器进行处理的。
发表评论