C语言基础练习题初学者可参考

1.字符反转

#include 
#include 
#include 
void swap(char *a,char *b)
{
    if(a==NULL&&b==NULL){
        printf("The ginseng error");
        exit(EXIT_SUCCESS);//若为初学者此处用return ;也是可以的,不影响使用;
                            //exit 为退出这个进程
    }

    int temp=0;

    while(a

2.输出所有小于100的质数

#include >

int main(int argc, char const *argv[])
{
    int n=100;
    int i=0;
    int j=0;
    int a=0;

    for(i=1;i

3交换的方式三种

3.1第一种三杯水交换

#include 

int main(int argc, char const *argv[])
{
    int a=10;
    int b=20;
    int temp=0;

    temp=a;
    a=b;
    b=temp;

    printf("a=%d b=%d\n",a,b);
    return 0;
}

3.2第二种异或交换

#include 

int main(int argc, char const *argv[])
{
    int a=10;
    int b=20;
    int temp=0;

    a=a^b;
    b=a^b;
    a=a^b;

    printf("a=%d b=%d\n",a,b);
    return 0;
}

3.3第三种交换//注意越界数值不能太大

#include 

int main(int argc, char const *argv[])
{
    int a=10;
    int b=20;
    int temp=0;

    b=a+b;
    a=b-a;
    b=b-a;

    printf("a=%d b=%d\n",a,b);
   

4.练习: 1.设计一个程序,实现功能: 输入一个字符, 如果是大写的,就转换成小写的输出 如果是小写的,就转换成大写输出 如果是数字,就 * 10 输出 如果是其他字符,都输出 # a --> A B --> b 2 --> 20 ( --> #

#include

int main(int argc, const char *argv[])
{
    char v = 0;
    scanf("%c", &v);
    getchar();
 
    if (v >= 'A' && v <= 'Z'){
        v += 32;
        printf("%c\n", v);
    }else if (v >= 'a' && v <= 'z'){
        v -= 32;
        printf("%c\n", v);
    }else if (v >= '0' && v <= '9'){
        v -= '0'; 
        v *= 10;
        printf("%d\n", v);
    }else{
        printf("%c\n", '#');
    }

    return 0;
}

5ifelse语句使用

练习: 编写程序计算身高 每个做父母的都关心自己孩子成人后的身高, 据有关生理卫生知识与数理统计分析表明, 影响小孩成人后身高的因素有遗传、饮食习惯与坚持体育锻炼等。 小孩成人后身高与其父母身高和自身性别密切相关。 设faHeight为其父身高,moHeight为其母身高,身高预测公式为: 男性成人时身高 = (faHeight + moHeight) * 0.54(cm) 女性成人时身高 = (faHeight * 0.923 + moHeight) / 2(cm)此外,如果喜爱体育锻炼,那么在原基础上可增加身高2% 如果有良好的卫生饮食习惯,那么在原基础上可增加身高1.5% 程序要求:父亲的身高与母亲的身高、小孩的性别、是否喜爱体育锻 炼 和是否有良好的卫生饮食习惯也从键盘上输入,最终输出预测的 身高。 提示:小孩性别的输入方式,可在屏幕给出提示“请输入小孩的性别 (男孩输入1,女孩输入0):”, 然后通过if语句来判断从键盘输入的字符是1还是0。 是否喜爱体育锻炼也可以通过类似的方式实现。

#include 

int main(int argc, const char *argv[])
 {
    double faHeight = 0;
    double moHeight = 0;
    double childHeight = 0;
    double pe_temp = 0,food_temp = 0;//用来记录身高的曾量
    int sex = 0; //性别 1男 0女
    int PE = 0; //体育运动 1喜欢 0不喜欢
    int FOOD = 0;//饮食习惯 1好习惯 0不好习惯

    printf("请输入父亲的身高:");
    scanf("%lf", &faHeight);
    printf("请输入母亲的身高:");
    scanf("%lf", &moHeight);
    printf("请输入孩子的性别(1男生 0女生):");
    scanf("%d", &sex);

    if(1 == sex){
    childHeight = (faHeight + moHeight) * 0.54;
    }else{
    childHeight = (faHeight * 0.923 + moHeight) / 2;
    }

    printf("请输入是否喜欢体育运动(1喜欢 0不喜欢):");
    scanf("%d", &PE);
    printf("请输入是否有好习惯(1有 0没有):");
    scanf("%d", &FOOD);

    if(1 == PE){
    pe_temp = childHeight * 0.02;
    }
    if(1 == FOOD){
    food_temp = childHeight * 0.015;
    }
    childHeight = childHeight + pe_temp + food_temp;
    printf("预测的孩子的身高为:%.3lf\n",childHeight);

    return 0;
    }

6.简易计算器实现

.编写代码,实现简易计算器功能(操作数 是整数即可 + - * / %): scanf("%d %c %d",); 输入:5 + 2 输出:7 输入:10 % 3 输出:1

 #include 

 int main(int argc, const char *argv[])
 {
    int num1 = 0, num2 = 0;
    char operator = 0;

    scanf("%d %c %d", &num1, &operator, &num2);
    switch(operator){
        case '+':
            printf("%d + %d = %d\n", num1, num2, num1+num2);
            break;
        case '-':
            printf("%d ‐ %d = %d\n", num1, num2, num1-num2);
            break;
        case '*':
            printf("%d * %d = %d\n", num1, num2, num1*num2);
            break;
        case '%':
            printf("%d %% %d = %d\n", num1, num2, num1%num2);
            break;
        case '/':
            printf("%d + %d = %.3lf\n", num1, num2, (double)num1/(double)num2);
            break;
        default:
            printf("我仅支持 + ‐ * / %%\n");
            break;
        }

    return 0;
 }

7学生成绩等级管理

#include 

 int main(int argc, const char *argv[])
 {
    int score = 0;
    scanf("%d", &score);
    getchar();

    switch(score/10){
        case 10:
        case 9:
            printf("A\n");
            break;
        case 8:
            printf("B\n");
            break;
        case 7:
            printf("C\n");
            break;
        default:
            printf("不及格\n");
            break;
    }

    return 0;
 }

8.使用while循环,实现 1~100 求和。

#include 

int main(){
    int i = 1, sum = 0;
    while(i<=100){
        sum += i;
        i++;
    }
    printf("sum = %d\n",sum);
    return 0;
 }

9..猴子吃桃

#include 

int main(){
    int sum = 1;
    int i = 0;
    while(i<9){
        printf("第 %d 天,有 %d 个桃\n", 10-i, sum);
        sum = (sum+1)*2;
        i++;
    }
    printf("第 %d 天,有 %d 个桃\n", 10-i, sum);
    return 0;
}

10.水仙花

#include 

 int main(int argc, const char *argv[])
 {
    int i = 0;
    int ge = 0;
    int shi = 0;
    int bai = 0;

    for(i = 100; i < 1000; i++){

        ge = i % 10;
        shi = i / 10 % 10;
        bai = i / 100;

        if(ge*ge*ge + shi*shi*shi + bai*bai*bai == i){
            printf("%d\n", i);
        }
    }
    return 0;
 }

11排版打出下面这种结果

C语言基础练习题初学者可参考_第1张图片

#include 

int main(int argc, char const *argv[])
{
    char ch='A';
    int i=0;
    int j=0;
    int a=0;
    for(i=0;i<8;i++){
        
        for(j=0;j

12.输入一个数,输出这个数的所有因子。

#include 

 int main(int argc, const char *argv[])
 {
    int num = 0;
    scanf("%d", &num);
    getchar();
  
    for(int i= 1; i <= num; i++){
        if(num%i == 0){
            printf("%d\n", i);
        }
    }

 return 0;
 }

13完美数

#include 

 int main(int argc, const char *argv[])
 {
    int i = 0;
    int j = 0;
    int sum = 0;

    for(i = 1; i < 1000; i++){
        sum = 0;
        for(j = 1; j < i; j++){
            if(i%j == 0){       
                sum += j;
            }
        }       
        if(sum == i){
            printf("%d\n", i);
        }
    }
 return 0;
 }

13练习: 1.定义一个10个长度的int数组,并全部初始化成0, 循环给数组成员赋值,赋的值来自键盘输入; 输出数组中最大的元素及最大元素的下标。

 #include 
 int main(){
    int arr[10] = {0};
    int i = 0;
    int max_index = 0;

    for(i = 0; i < 10; i++){
        scanf("%d", &arr[i]);
    }
    
    for(i = 1; i < 10; i++){
        if(arr[i] > arr[max_index]){
            max_index = i;
        }
    }
    
    printf("max_value = %d , max_index = %d\n",arr[max_index],max_index);
    return 0;
 }

14冒泡排序

#include 

 int main(int argc, const char *argv[])
{
    int s[10] = {23,45,65,78,90,55,33,17,96,54};
    int i = 0;
    int j = 0;
    int temp = 0;
    int flags=0;
    int len = sizeof(s)/sizeof(int);

    for(i = 0; i < len; i++){
    printf("%d ", s[i]);
    }

    printf("\n");

    for(j = 0; j < len-1; j++){
        flags=0;
        for(i = 0; i < len-1-j; i++){
            if(s[i] > s[i+1]){
                temp = s[i];
                s[i] = s[i+1];
                s[i+1] = temp;
                flags=1;
            }
        }
        if(flags==0){
             break;
         }        
    }

    for(i = 0; i < len; i++){
        printf("%d ", s[i]);
    }

    printf("\n");

    return 0;
 }

15strlen函数

#include 
int mystrlen(char *num)
{
    int i=0;
    while(*num){
        i++;
        num++;
    }

    return i;
}

int main(int argc, char const *argv[])
{
    char num[20]="i love china";
    int length=0;

    length=mystrlen(num);

    printf("%d\n",length);
    return 0;
}

16strcat

#include 
void  mystrcat(char *dest, char *src)
{
    //1.判断地址是否是空,如果是空就退出
    if(dest == NULL || src == NULL){
        return ;
    }   

    //2.找到dest的'\0'                                           
    while(*dest){
        dest++;
    }   

    //3.拷贝数据
    while(*src){
        *dest++ = *src++;
    }   

    //4.给dest赋结束符号
    *dest  = '\0';

}

int main(int argc, const char *argv[])
{
    char arr[50] = {0};
    char brr[100] = {0};
    printf("input string (arr) > ");
    gets(arr);
    printf("input string (brr) > ");
    gets(brr);

    mystrcat(brr,arr);

    printf("brr = %s\n",brr);

    return 0;
}

16strcpy

#include 
#include 
#include 

char* mystrcpy(char* arr, char* brr)
{
    if (NULL == arr || NULL == brr){
        printf("传参错误\n");
        exit(-1);
    }

    char* cp = arr;

    while (*cp++ = *brr++);

    return arr;
}

int main(int argc, char const *argv[])
{
    char arr[100] = "asdasd";
    char brr[200] = "112321312";

    mystrcpy(arr, brr);

    printf("%s\n",arr);
    return 0;
}

17strcmp

#include 

int mystrcmp(char *a,char *b)
{
    while(*a&&*b&&*a==*b){
        a++;
        b++;
    }

    if((*a-*b)>0){
        return (*a - *b);
    }else if((*a-*b)<0){
        return (*a - *b);
    }else{
        return 0;
    }
}

int main(int argc, char const *argv[])
{
    char a[20]={0};
    char b[20]={0};
    int flag=0;

    printf("Please enter the value of a >");
    gets(a);
    printf("Please enter the value of b >");
    gets(b);

    flag=mystrcmp(a,b);

    if(flag>0){
        printf("a>b\n");
    }else if(flag<0){
        printf("a

18编写atoi函数

#include 

void my_gets(char *a,int n)
{
	int i=0;
	while(i='0'&&(*s)<='9'){
		num=num*10+*s-'0';
		s++;
	}

	return sig*num;
}

int main(int argc, const char *argv[]){
	char array[50]={0};

	my_gets(array,100);


	printf("%d\n",my_atoi(array));
	return 0;
}

19斐波那契数列

#include 

int main(int argc, const char *argv[]){
	int s[20]={1,1};
	int i=0;

	for(i=2;i<20;i++){
		s[i]=s[i-1]+s[i-2];
	}

	for(i=0;i<20;i++){
		printf("%d  ",s[i]);
	}
	puts("");
	
	return 0;
}
#include 

int feibo(int n)
{
    if (n <= 2){
        return 1;
    }

    return feibo(n - 2) + feibo(n - 1);
}



int main(int argc, char const *argv[])
{
    
    printf("%d\n", feibo(8));

    return 0;
}

20数组中找最大值

#include 

int main(int argc, const char *argv[]){
	int arr[10]={0};
	int i=0;
	for(i=0;i<10;i++){
		scanf("%d",&arr[i]);
	}
	int max=0;
	for(i=0;i<10;i++){
		if(arr[i]>arr[max]){
			max=i;
		}
	}

	printf("%d %d\n",max,arr[max]);
	return 0;
}

21九九乘法表

#include 

int main(int argc, char const *argv[])
{
    int i=0;
    int j=0;

    for(i=1;i<10;i++){
        for(j=1;j<=i;j++){
            printf("%d*%d=%d ",j,i,i*j);
        }
        puts("");
    }
    return 0;
}

22输出一个二进制:

#include 

int main(int argc, char const *argv[])
{
    int num;
    int flag;
    printf("请输入你的数字:");
    scanf("%d", &num);
    int i=0;
    int sum[128] = {0};

    while (num!=0){
        flag = num % 2;
        sum[i] = flag;
        num/=2;
        i++;
    }
    
    for (i = i-1; i>=0; i--){
        printf("%d ",sum[i]);
    }
    puts("");
    return 0;
}

23输入小写的字符,统计每个小写字符的个数:

#include 

int get_index(char ch)
{
    return ch - 'a';
}

int main(int argc, char const *argv[])
{
    char s[128] = {0};
    int i=0;
    int index;
    unsigned int count[32] = {0};

    printf("请输入您的字符串>>");
    scanf("%s", s);



    while (0 != s[i]){
        index = get_index(s[i]);
        count[index]++;
        i++;
    }

    for (i = 0; i<26; i++){
        printf("[%c] [%d]\n",i + 'a', count[i] );
    }
    return 0;
}

24万年历

#include 
#include 
#include 

int main (){
    int year = 0, month = 0, day = 0;
    int hour = 0, min = 0, sec = 0;
    scanf("%d%d%d%d%d%d", &year, &month, &day
    , &hour, &min, &sec);//输入时 以空格分隔
while(1){
    system("clear");//调用clear命令清屏,实现单行显示
    printf("%4d-%02d-%02d %02d:%02d:%02d\n",
        year, month, day, hour, min, sec);//%02d 是格式化输出  后面讲
    sec++;
    if(60 == sec){
        sec = 0;
        min++;
        if(60 == min){
            min = 0;
            hour++;
            if(24 == hour){
                hour = 0;
                day++;
                //31天的月
                if(1 == month || 3 == month || 5 == month || 7 == month || 8 == month
                    || 10 == month || 12 == month){
                        if(32 == day){
                            day = 1;
                            month++;
                        }
                //30天的月
                }else if(4 == month || 6 == month || 9 == month || 11 == month || 8 == month){
                        if(31 == day){
                            day = 1;
                            month++;
                        }
                //闰年的2月
                }else if((year%4==0 && year%100!=0) || year%400==0){
                        if(30 == day){
                            day = 1;
                            month++;
                        }
                //平年的2月
                }else{
                        if(29 == day){
                            day = 1;
                            month++;
                        }
                }
                if(13 == month){
                    month = 1;
                    year++;
                }
            }
        }
    }
    sleep(1);//休眠1秒
}
    return 0;
}

25比较两个字符串最长有多少个连续字符相等

#include 
#include 

int compare(char* arr, char* brr)
{
    int i,j;
    int len = 0;
    int max = 0;
    int temp = 0;

    for (i = 0; i < strlen(arr); i = temp, i++){
         temp = i;
        for (j = 0, len = 0; j < strlen(brr); j++){
            while (arr[i] == brr[j] && arr[i] != '\0' && brr[j] != '\0'){
                len++;
                i++;
                j++;
                max = max > len ? max : len;      
            }
        }
    }

    return max;
}


int main(int argc, char const *argv[])
{
    char arr[128] = "abcdefgddd";
    char brr[128] = "ooooabcdefgdd";

    printf("%d\n", compare(arr, brr));
    return 0;
}

26统计一个字符串中不重复的字符串的最大长度:

#include 
#include 
#include 
#include 

int get_maxlen(char *s)
{
    int hash[128] = {0};
    int right = 0,left = 0;
    int max = 0;

    while(right < strlen(s)){
        
        if (hash[s[right]] > 0){
            hash[s[left]] = 0;
            left++;
        }else {
            hash[s[right]] = 1;
            right++;
            max = (right - left) > max ? (right - left) : max;
        }
    }

    return max;
}


int main(int argc, char const *argv[])
{
  char arr[128] = {0};
  printf("input >>");
  scanf("%s", arr);

  printf("%d\n", get_maxlen(arr));

  return 0;
}

27打出下划线加字母

F
_FE
__FED
___FEDC
____FEDCB
_____FEDCBA
#include 

int main(int argc, char const *argv[])
{
    
    int i, j, a;
    char ch = 'F';

    for ( i = 0; i < 6; i++){
        
        for (j = 1; j <= i; j++){
            printf("_");
        }

        for (a = 0, ch = 'F'; a <= i; a++){
            printf("%c", ch--);
        }
        puts("");
    }
    return 0;
}

28将char类型转换为int类型

#include 

int main(int argc, char const *argv[])
{
    char arr[12] = "123456";
    int i = 0;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
    int sum = 0;

    while (arr[i] != 0){
        sum = sum*10 + arr[i] - '0';
        i++;
    }

    printf("%d\n", sum);
    return 0;
}

29将int类型转换为char类型

#include 
#include 
#include 

int main(int argc, char const *argv[])
{
    
    int data = 1234567;
    char str[10] = {0};
    char ch[10] = {0};
    int i = 0;

    while (data){
        str[i] = data % 10 + '0';
        i++;
        data = data / 10;
    }

    while (i){
        printf("%c", str[--i]);
    }
    puts("");
    return 0;
}

30二分查找

#include 

int binary_search(int *arr, int p, int q, int ele)
{
    int mid = 0;

    if (p > q){
        return 0;
    }

    mid = p + (q - p) / 2;

    if (ele == arr[mid]){
        return mid;
    } 

    if (ele < arr[mid]){

        return binary_search(arr, p, mid - 1, ele);
    }else {
        return binary_search(arr, mid + 1,  q, ele);
    }
}

int main(int argc, char const *argv[])
{
    int arr[10] = {10, 14, 19, 26, 27, 31, 33, 35, 42, 44};

    printf("%d\n", binary_search(arr, 0, 9, 31));
    return 0;
}

31选择排序

#include 
#include 

void choose_sort(int *arr)
{   
    if (NULL == arr){
        printf("传参错误\n");
        exit(-1);
    }

    int i;
    int j;
    int max = 0;
    int temp;

    for (i = 0; i < 4; i++){
        max = i;
        for (j = i + 1; j < 5; j++){
            if (arr[j] > arr[max]) max = j;
        }

        if (max != i){
            temp = arr[max];
            arr[max] = arr[i];
            arr[i] = temp;
        }
    }

    return;
}

int main(int argc, char const *argv[])
{
    int arr[5] = {11, 1, 20, 2, 300};

    choose_sort(arr);


    for (int i = 0; i < 5; i ++){
        printf("%d ", arr[i]);
    }

    puts("");
    return 0;
}

32实现memcpy

#include 


void* memcpy(void* dest, const void* src, size_t num)
{
    if (NULL == dest || NULL == src){
        return NULL;
    }

    char* pDest = (char*)dest;
    char* pSrc = (char*)src;

    for (int i = 0; i < num; i++){
        *(pDest + i) = *(pSrc + i);
    }

    return dest;
}

int main(){
	int arr[4] = { 4, 6, 8, 7 };
	int arr2[4] = { 0 };
	memcpy(arr2, arr, 16);				//调用  16是字节数
	for (int i = 0; i < 4; i++){		//数组循环输出
		printf("%d ", arr2[i]);
	}
	return 0;
}

33十六进制转10进制

#include 

int main(int argc, char const *argv[])
{
    char a[100] = {0};
    int i =0, re = 0;
    printf("Enter a string:");
    fgets(a, 100, stdin);

    while (a[i]){

        if (a[i] >= '0' && a[i] <= '9'){
            re = re * 16 + a[i] - '0';
        }else if(a[i] >= 'a' && a[i] <= 'f'){
            re = re * 16 + a[i] + 10 -'a';
        }else if(a[i] >= 'A' && a[i] <= 'F'){
            re = re * 16 + a[i] + 10 - 'A';
        }
        i++;
    }

    printf("number=%d\n", re);

    return 0;
}

34十进制转十六进制

#include 

int main(int argc, char const *argv[])
{
    char a[32] = "0123456789ABCDEF";
    char b[100];
    int n;
    int cnt = 0;;
   
    scanf("%d", &n);

    if (n == 0){
        printf("0\n");
    }

    while (n){
        b[++cnt] = a[n % 16];
        n = n / 16;
    }

    for (int i = cnt; i > 0; i--){
        printf("%c", b[i]);
    }
    puts("");


    return 0;
}

35将16进制的字符串,两个两个转化为16进制的数值

#include
#include
//这个函数会把字符转成,16进制的本身的值,例如 '1'->0x1 'b'-> 0xb
int sthvalue(char c)
{
        int value;
        if((c >= '0') && (c <= '9'))
                value = 48;
        else if ((c >= 'a') && (c <='f'))
                value = 87;
        else if ((c >= 'A') && (c <='F'))
                value = 55;
        else {
                printf("invalid data %c",c);
                return -1;
        }
        return value;
}
/*转化函数,把字符串和一个数组当做参数,这个函数会把str的值,每两个组合成一个16进制的数*/
int strtohex(char *str, char *data)
{
        int len =0;
        int sum =0;
        int high=0;
        int low=0;
        int value=0;
        int j=0;
        len = strlen(str);//获取字符串的字符个数
        //char data[256] = {0};
        printf("%d\n", len);
        //在for循环中,从0开始,每两个数组成一个16进制,高4位和低4位,然后放技能数组中去
        for(int i=0; i

36时间戳和标准时间直接的相互转换

#include 
#include 
#include 
#include 

/*标准时间转换为时间戳*/
int standard_to_stamp(char *str_time)
{
	struct tm stm;
	int iY,iM,iD,iH,iMin,iS;
	int i;
	memset(&stm,0,sizeof(stm));
	int arr[5] = {4, 7, 10, 13, 16};

	//Check whether the entered time format is correct
	if (strlen(str_time) != TIME_LEN){
		printf("The entered time format is incorrect\n"
		"Please enter in the correct format for example: 2023-02-03 13:54:00\n");
		exit(EXIT_FAILURE);
	}

	for (i = 0; i < strlen(str_time); i++){
		if (str_time[i] < '0' || str_time[i] > '9'){
			if (!(i == arr[0] || i == arr[1] || i == arr[2] || i == arr[3] || i== arr[4])){
				printf("The entered time format is incorrect\n"
				"Please enter in the correct format for example: 2023-02-03 13:54:00\n");
				exit(EXIT_FAILURE);
			}
			
		}

		if (i < 5){
			if (!((str_time[arr[i]] == ' ') || (str_time[arr[i]] == '.') || (str_time[arr[i]] == '-') || (str_time[arr[i]] == ':'))){
				printf("The entered time format is incorrect\n"
				"Please enter in the correct format for example: 2023-02-03 13:54:00\n");
				exit(EXIT_FAILURE);
			}	
		}
		
		
	}
	

	iY = atoi(str_time);
	iM = atoi(str_time+5);     
	iD = atoi(str_time+8);
	iH = atoi(str_time+11);
	iMin = atoi(str_time+14);
	iS = atoi(str_time+17);

	if ((iY < 1900)){
		printf("The input year cannot be less than 1900\n");
		exit(EXIT_FAILURE);
	}
	
	if ((iM < 1) || (iM > 12)){
		printf("The value ranges from 1 to 12 months\n");
		exit(EXIT_FAILURE);
	}

	switch(iM)
	{
		 case 1: case 3: case 5: case 7: case 8: case 10: case 12:
		 	 if(iD<1 || iD>31) {
		 	 	printf("Each month of 1, 3, 5, 7, 8, 10, 12 has 31 days\n");
				exit(EXIT_FAILURE);
		 	 }
		 	 break;
		 case 4: case 6: case 9: case 11:
		 	 if(iD<1 || iD>30) {
		 	 	printf("Each month of 4, 6, 9, 11 has 30 days\n");
				exit(EXIT_FAILURE);
		 	 }
		 	 break;
		 case 2:
		   if((iY % 4 ==0 && iY % 100 !=0) || iY % 400 ==0)	{
				if(iD<1 || iD>29){
					printf("February should have 29 days if it is a leap year\n");
					exit(EXIT_FAILURE);
				}
		   }else{
				if(iD<1 || iD>28) {
					printf("February would have 28 days in a normal year\n");
					exit(EXIT_FAILURE);    
				}
		   }
		 	 break;
	}

	if (iH > 24 || iH < 0){
		printf("Hours range from 0 to 24\n");
		exit(EXIT_FAILURE);
	}
	
	if (iMin < 0 || iMin > 59){
		printf("The value ranges from 0 to 59 minutes\n");
		exit(EXIT_FAILURE);
	}
	
	if (iS < 0 || iS > 59){
		printf("The value ranges from 0 to 59 seconds\n");
		exit(EXIT_FAILURE);
	}
	

	stm.tm_year=iY-1900;
	stm.tm_mon=iM-1;
	stm.tm_mday=iD;
	stm.tm_hour=iH;
	stm.tm_min=iMin;
	stm.tm_sec=iS;
	
	return (int)mktime(&stm);
}

/*时间戳转换为标准时间*/
typedef struct times
{
	int Year;
	int Mon;
	int Day;
	int Hour;
	int Min;
	int Second;
}Times;

Times stamp_to_standard(int stampTime)
{
	time_t tick = (time_t)stampTime;
	struct tm tm;
	char s[100];
	Times standard;
	tm = *localtime(&tick);
	strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S", &tm);
	printf("时间戳为:%d 转换成标准时间为: %s\n", (int)tick, s);

	standard.Year = atoi(s);
	standard.Mon = atoi(s+5);
	standard.Day = atoi(s+8);
	standard.Hour = atoi(s+11);
	standard.Min = atoi(s+14);
	standard.Second = atoi(s+17);
	
	return standard;
}

int main(int argc, char **argv)
{
	int a =0;

	printf("输入的标准时间是: %s \n",argv[1]);
	
	a=standard_to_stamp(argv[1]);
	printf("标准时间转换为时间戳: %d\n",a);

	stamp_to_standard(a);	

	return  0;
}

37将10进制数转换为16进制的字符

char  buffer [33]; 
char  * inttohex( int  aa)
{
     static  int  i = 0;
     if  (aa < 16)             
     {
         if  (aa < 10)         
             buffer[i] = aa +  '0' ;
         else
             buffer[i] = aa - 10 +  'A' ;
         buffer[i+1] =  '\0' ;  
     }
     else
     {
         inttohex(aa / 16);    
         i++;                 
         aa %= 16;            
         if  (aa < 10)        
             buffer[i] = aa +  '0' ;
         else
             buffer[i] = aa - 10 +  'A' ;
     }
     return  (buffer);
}

38判断你输入的是否是mac地址

#include 
#include 

int main() {
    regex_t regex;
    int reti;
    char ip[] = "11:ff:22:ff:ff:ff";

    reti = regcomp(®ex, "^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$", REG_EXTENDED);
    if (reti) {
        char error_msg[100];
        regerror(reti, ®ex, error_msg, sizeof(error_msg));
        fprintf(stderr, "Could not compile regex: %s\n", error_msg);
        return 1;
    }

    reti = regexec(®ex, ip, 0, NULL, 0);
    if (!reti) {
        printf("Match\n");
    } else if (reti == REG_NOMATCH) {
        printf("No match\n");
    } else {
        char error_msg[100];
        regerror(reti, ®ex, error_msg, sizeof(error_msg));
        fprintf(stderr, "Regex match failed: %s\n", error_msg);
        return 1;
    }

    regfree(®ex);
    return 0;
}

39判断你输入的是否是一个正确的ip地址

#include 
#include 

int isValidIpAddress(char* ipAddress) {
    regex_t regex;
    int reti;
    
    // 编译正则表达式
    reti = regcomp(®ex, "^([0-9]{1,3}\\.){3}[0-9]{1,3}$", 1);
    
    if(reti) {
        fprintf(stderr, "Could not compile regex.\n");
        return -1;
    }
    
    // 匹配正则表达式
    reti = regexec(®ex, ipAddress, 0, NULL, 0);
    
    // 释放正则表达式
    regfree(®ex);
    
    if(!reti) {
        return 1;
    }
    else {
        return 0;
    }
}

int main() {
    char ipAddress[] = "192.168.1.1";
    int isValid = isValidIpAddress(ipAddress);
    
    if(isValid) {
        printf("%s is a valid IP address.\n", ipAddress);
    }
    else {
        printf("%s is not a valid IP address.\n", ipAddress);
    }
    
    return 0;
}

40 getopt_long的使用方法

#include 
#include 
#include 

int main(int argc, char *argv[]) {
    int opt;
    int option_index = 0;
    struct option long_options[] = {
        {"help", no_argument, 0, 'h'},
        {"version", no_argument, 0, 'v'},
        {"output", required_argument, 0, 'o'},
        {"input", required_argument, 0, 'i'},
        {0, 0, 0, 0} // 最后一项是必需的,用于指示选项数组结束
    };

    while ((opt = getopt_long(argc, argv, "hvo:i:", long_options, &option_index)) != -1) {
        switch (opt) {
            case 'h':
                printf("帮助信息:...\n");
                break;
            case 'v':
                printf("版本信息:...\n");
                break;
            case 'o':
                printf("输出文件:%s\n", optarg);
                break;
            case 'i':
                printf("输入文件:%s\n", optarg);
                break;
            case '?':
                // 当出现不认识的选项或缺少必要的参数时,会返回 '?',并输出错误信息到 stderr
                fprintf(stderr, "无效的选项或缺少参数:%c\n", optopt);
                break;
            default:
                // 如果使用了没有在选项数组中定义的选项,则会执行 default 分支
                fprintf(stderr, "未处理的选项:%c\n", opt);
                break;
        }
    }

    // 处理剩余的非选项参数(不带'-'或'--'的参数)
    for (int i = optind; i < argc; i++) {
        printf("非选项参数:%s\n", argv[i]);
    }
    return 0;
}

41 判断从终端输入的密码是否正确

#include 
#include 
#include 
#include 

int main(int argc, char* argv[])
{
    char buf[1024] = {0};
    struct termios old_term, new_term;
    int count = 0;
    int j = 0;
    char ch = 0;

    tcgetattr(STDIN_FILENO, &old_term);
    new_term = old_term;
    new_term.c_lflag &= ~(ICANON | ECHO);
    tcsetattr(STDIN_FILENO, TCSANOW, &new_term);
    memset(buf, 0, 1024);
    printf("Password:");
    while(1) {  
        ch = getchar();

        if (ch == '\n') {
            if (!strcmp(buf, "asd"))
                break;
            else {
                memset(buf, 0, 1024);
                j = 0;
                printf("\nerror password.\n");
            }
            printf("Password:");
            ++count;
            if (count >= 3)
                return 0;
        }else {
            buf[j++] = ch;
            if (j >= 1024) {
                memset(buf, 0, 1024);
                j = 0;
                printf("\nerror Invalid password.\n");
                printf("Password:");
            }
        }

    }

    tcsetattr(STDIN_FILENO, TCSANOW, &old_term);
    printf("\n");

}

42 生成一个1-100之间的随机数

#include 
#include 
#include 

int main() {
    int min_value = 1;   // 随机数的最小值
    int max_value = 100; // 随机数的最大值

    // 使用当前时间作为随机数种子
    srand(time(NULL));

    // 生成一个介于min_value和max_value之间的随机数
    int random_number = min_value + rand() % (max_value - min_value + 1);

    printf("随机数: %d\n", random_number);

    return 0;

你可能感兴趣的:(c语言,c语言,算法,c++)