C 语言实例 – 交换两个数的值

使用临时变量

以下实例演示了交换两个浮点数的值。
#include <stdio.h>

int main()
{
      double firstNumber, secondNumber, temporaryVariable;

      printf("输入第一个数字: ");
      scanf("%lf", &firstNumber);

      printf("输入第二个数字: ");
      scanf("%lf",&secondNumber);

      // 将第一个数的值赋值给 temporaryVariable
      temporaryVariable = firstNumber;

      // 第二个数的值赋值给 firstNumber
      firstNumber = secondNumber;

      // 将 temporaryVariable 赋值给 secondNumber
      secondNumber = temporaryVariable;

      printf("\n交换后, firstNumber = %.2lf\n", firstNumber);
      printf("交换后, secondNumber = %.2lf", secondNumber);

      return 0;
}

不使用临时变量

不使用临时变量交换两个整数的值:

#include <stdio.h>

int main() {
   int a, b;

   a = 11;
   b = 99;

   printf("交换之前 - \n a = %d, b = %d \n\n", a, b);

   a = a + b;  // ( 11 + 99 = 110)  此时 a 的变量为两数之和,b 未改变
   b = a - b;  // ( 110 - 99 = 11)  
   a = a - b;  // ( 110 - 11 = 99)

   printf("交换后 - \n a = %d, b = %d \n", a, b);
}

C 语言实例 – 计算 int, float, double 和 char 字节大小

使用 sizeof 操作符计算int, float, double 和 char四种变量字节大小。

sizeof 是 C 语言的一种单目操作符,如C语言的其他操作符++、--等,它并不是函数。

sizeof 操作符以字节形式给出了其操作数的存储大小
#include <stdio.h>

int main()
{
    int integerType;
    float floatType;
    double doubleType;
    char charType;

    // sizeof 操作符用于计算变量的字节大小
    printf("Size of int: %ld bytes\n",sizeof(integerType));
    printf("Size of float: %ld bytes\n",sizeof(floatType));
    printf("Size of double: %ld bytes\n",sizeof(doubleType));
    printf("Size of char: %ld byte\n",sizeof(charType));

    return 0;
}

计算 long long, long double 字节大小

#include <stdio.h>
int main()
{
    int a;
    long b;
    long long c;

    double e;
    long double f;

    printf("Size of int = %ld bytes \n", sizeof(a));
    printf("Size of long = %ld bytes\n", sizeof(b));
    printf("Size of long long = %ld bytes\n", sizeof(c));

    printf("Size of double = %ld bytes\n", sizeof(e));
    printf("Size of long double = %ld bytes\n", sizeof(f));

    return 0;
}

编译测试。

C 语言实例 – 数值比较

比较两个数

以下实例中定义了两个整数变量,并使用 if 来比较两个数值,可以先看下逻辑图:

#include <stdio.h>

int main() {
   int a, b;

   a = 11;
   b = 99;

   // 也可以通过以下代码实现让用户在终端输入两个数
   // printf("输入第一个值:");
   // scanf("%d", &a);
   // printf("输入第二个值:");
   // scanf("%d", &b);

   if(a > b)
      printf("a 大于 b");
   else
      printf("a 小于等于 b");

   return 0;
}

比较三个数
以下实例中定义了两个整数变量,并使用 if 来比较三个数值,可以先看下逻辑图:

#include <stdio.h>

int main() {
   int a, b, c;

   a = 11;
   b = 22;
   c = 33;

   if ( a > b && a > c )
      printf("%d 最大", a);
   else if ( b > a && b > c )
      printf("%d 最大", b);
   else if ( c > a && c > b )
      printf("%d 最大", c);
   else   
      printf("有两个或三个数值相等");

   return 0;
}

测试看结果。

C 语言实例 – 两数相除

两数相除,如果有余数,输出余数。

#include <stdio.h>

int main(){

    int dividend, divisor, quotient, remainder;

    printf("输入被除数: ");
    scanf("%d", &dividend);

    printf("输入除数: ");
    scanf("%d", &divisor);

    // 计算商
    quotient = dividend / divisor;

    // 计算余数
    remainder = dividend % divisor;

    printf("商 = %d\n", quotient);
    printf("余数 = %d", remainder);

    return 0;
}

C语言实例8

ASCII 定义了 128 个字符。

分类:

一:0-31、127(删除键)是控制字符
二:空白字符:空格(32)、 制表符、 垂直制表符、 换行、 回车。
三:可显示字符:a-z、A-Z、0-9、~、!、@、、%、^、&、#、$、*、(、)、-、+、{、}、[、]、'、"、<、>、,、?、/、|、\、_、:、;、.,还有顿号、。
ASCII 表:

ASCII值 控制字符 ASCII值 控制字符 ASCII值 控制字符 ASCII值 控制字符
0 NUT 32 (space) 64 @ 96 、
1 SOH 33 ! 65 A 97 a
2 STX 34 " 66 B 98 b
3 ETX 35 # 67 C 99 c
4 EOT 36 $ 68 D 100 d
5 ENQ 37 % 69 E 101 e
6 ACK 38 & 70 F 102 f
7 BEL 39 , 71 G 103 g
8 BS 40 ( 72 H 104 h
9 HT 41 ) 73 I 105 i
10 LF 42 * 74 J 106 j
11 VT 43 + 75 K 107 k
12 FF 44 , 76 L 108 l
13 CR 45 - 77 M 109 m
14 SO 46 . 78 N 110 n
15 SI 47 / 79 O 111 o
16 DLE 48 0 80 P 112 p
17 DCI 49 1 81 Q 113 q
18 DC2 50 2 82 R 114 r
19 DC3 51 3 83 S 115 s
20 DC4 52 4 84 T 116 t
21 NAK 53 5 85 U 117 u
22 SYN 54 6 86 V 118 v
23 TB 55 7 87 W 119 w
24 CAN 56 8 88 X 120 x
25 EM 57 9 89 Y 121 y
26 SUB 58 : 90 Z 122 z
27 ESC 59 ; 91 [ 123 {
28 FS 60 < 92 / 124 |
29 GS 61 = 93 ] 125 }
30 RS 62 > 94 ^ 126 `
31 US 63 ? 95 _ 127 DEL

#include <stdio.h>
int main()
{
    char c;
    printf("输入一个字符: ");

    // 读取用户输入
    scanf("%c", &c);  

    // %d 显示整数
    // %c 显示对应字符
    printf("%c 的 ASCII 为 %d", c, c);
    return 0;
}

编译并运行看结果。

C语言实例7

输入两个浮点数,计算乘积。

#include <stdio.h>
int main()
{
    double firstNumber, secondNumber, product;
    printf("输入两个浮点数: ");

    // 用户输入两个浮点数
    scanf("%lf %lf", &firstNumber, &secondNumber);  

    // 两个浮点数相乘
    product = firstNumber * secondNumber;  

    // 输出结果, %.2lf 保留两个小数点
    printf("结果 = %.2lf", product);

    return 0;
}

编译执行看结果。

C语言实例6

使用 scanf() 来接收输入, printf() 与 %d 格式化输出整数。

#include <stdio.h>
int main()
{
    int firstNumber, secondNumber, sumOfTwoNumbers;

    printf("输入两个数(以空格分割): ");

    // 通过 scanf() 函数接收用户输入的两个整数
    scanf("%d %d", &firstNumber, &secondNumber);

    // 两个数字相加
    sumOfTwoNumbers = firstNumber + secondNumber;

    // 输出结果
    printf("%d + %d = %d", firstNumber, secondNumber, sumOfTwoNumbers);

    return 0;
}

编译运行看结果。

C 语言练习记录

前言

本来想写一篇日志,后来发现没有什么可以写的,就简单记录一下C语言的几个小练习,准备一个系列教程。

代码

demo1

#include <stdio.h>

int main()
{
        char greetings[6] = { 'H', 'e', 'l', 'l', 'o','\0'};

        printf("Greeting Message: %s\n", greetings);
        return 0;
}

demo2

#include <stdio.h>
#include <string.h>

int main()
{
        char str1[12] = "Hello";
        char str2[12] = "world";
        char str3[12];
        int len;
        strcpy(str3,str1);
        printf("strcpy(str3,str1): %s\n", str3);

        strcat(str1, str2);
        printf("strcat(str1,str2): %s\n", str1);

        len = strlen(str1);
        printf("strlen(str1) : %d\n", len);
        return 0;
}

demo3.c

#include<stdio.h>
#include<string.h>

struct Books
{
        char title[50];
        char author[50];
        char subject[100];
        int book_id;
};

int main()
{
        struct Books Book1;
        struct Books Book2;

        /* Book1 details */
        strcpy( Book1.title, "C Programming");
        strcpy( Book1.author, "liweibin");
        strcpy( Book1.subject, "C Programming Tutorial");
        Book1.book_id = 6495407;

        /* Book2 details */
        strcpy( Book2.title, "python");
        strcpy( Book2.author, "liweibin");
        strcpy( Book2.subject, "python Programming Tutorial");
        Book1.book_id = 6495409;

        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);

        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);

        return 0;
}

demo4.c


#include <stdio.h>
#include <string.h>

struct Books
{
        char title[50];
        char author[50];
        char subject[100];
        int book_id;
};

/* Declaration of function */
void printBook( struct Books book );

int main()
{
        struct Books Book1;
        struct Books Book2;

        strcpy(Book1.title, "C Programming");
        strcpy(Book1.author, "jacky");
        strcpy(Book1.subject, "Tutorial");
        Book1.book_id = 655121;

        strcpy(Book2.title, "Python Programming");
        strcpy(Book2.author, "jacky");
        strcpy(Book2.subject, "Programming Tutorial");
        Book2.book_id = 655122;

        printBook( Book1 );
        printBook( Book2 );
        return 0 ;
}

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);
}

demo5.c

#include <stdio.h>
#include <string.h>

struct Books
{
        char title[50];
        char author[50];
        char subject[50];
        int book_id;
};

void printBook( struct Books *book);
int main()
{
         struct Books Book1;
         struct Books Book2;

         strcpy(Book1.title, "C programming");
         strcpy(Book1.author, "jacky.li");
         strcpy(Book1.subject, "C Progarmming Tutorial");
         Book1.book_id = 654121;

         strcpy(Book2.title, "Python programming");
         strcpy(Book2.author, "jacky.li");
         strcpy(Book2.subject, "Python Progarmming Tutorial");
         Book2.book_id = 654122;

         printBook( &Book1);
         printBook( &Book2);

         return 0;
}
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);
}

demo6.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;
}

demo7.c

#include <stdio.h>
#include <string.h>

union Data
{
        int i;
        float f;
        char str[20];
};

int main()
{
        union Data data;
        data.i = 10;
        data.f = 220.5;
        strcpy( data.str, "C Programming");

        printf("data.i: %d\n", data.i);
        printf("data.f: %f\n", data.f);
        printf("data.str: %s\n", data.str);

        printf("Memory size occupied by data: %d\n", sizeof(data));
        return 0;
}

demo8.c


#include <stdio.h>
#include <string.h>

union Data
{
        int i;
        float f;
        char str[20];
};

int main()
{
        union Data data;
        data.i = 10;
        printf("data.i: %d\n", data.i);

        data.f = 220.5;
        printf("data.f: %f\n", data.f);

        strcpy( data.str, "C Programming");
        printf("data.str: %s\n", data.str);

        printf("Memory size occupied by data: %d\n", sizeof(data));
        return 0;
}

demo9.c

#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;
        strcpy( book.title, "C programming");
        strcpy( book.author, "Jacky.li");
        strcpy( book.subject, "progamming language");
        book.book_id = 9527;

        printf("书标题: %s\n", book.title);
        printf("书作者:%s\n", book.author);
        printf("书类目: %s\n", book.subject);
        printf("书ID: %d\n", book.book_id);

        return 0;
}

demo10.c

#include <stdio.h>

int main()
{
        int c;

        printf("Enter a value:");
        c = getchar();

        printf("\nYou entered: ");
        putchar(c);
        printf("\n");
        return 0;
}

demo11.c

#include <stdio.h>

int main()
{
        char str[100];
        char str2[100];

        printf("Enter a value:");
        gets(str);
        printf("Why?");
        gets(str2);

        printf("\nYou said: ");
        puts(str);
        puts(str2);
        return 0;
}

demo12.c


#include <stdio.h>

int main()
{
        char str[100];
        int i;

        printf("Enter a value: ");
        scanf("%s %d", str, &i);

        printf("\nYou entered: %s %d \n", str, i);
        return 0;
}

demo13.c

#include <stdio.h>

int main()
{
        FILE *fp = NULL;

        fp = fopen("/sys/class/thermal/thermal_zone0/temp", "r");
        fprintf(fp, "This is testing for fprintf...\n");
        fclose(fp);
}

demo14.c

#include <stdio.h>

int main()
{
        FILE *fp = NULL;
        char buff[255];

        fp = fopen("/sys/class/thermal/thermal_zone0/temp", "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);
        return 0;
}

demo15.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
   FILE *fp2 = NULL;
   float temp, deg;
   int n;

   fp2 = fopen("/sys/class/thermal/thermal_zone0/temp", "r");
   n = fscanf(fp2, "%f", &deg);
   fclose(fp2);
   temp = deg / 1000;
   fputs(temp, fp);
   printf("Temp is: %f\n", temp);
   return 0;
}

demo16.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int fibonaci(int i)
{
        if(i==0)
        {
                return 0;
        }
        if(i==1)
        {
                return 1;
        }
        return fibonaci(i-1) + fibonaci(i-2);
}

int main()
{
        FILE *fp2 = NULL;
        float temp, deg;
        int n;
        int i;
        fp2 = fopen("/sys/class/thermal/thermal_zone0/temp", "r");
        for (i=0; i<100;i++)
        {
                n = fscanf(fp2, "%f", &deg);
                temp = deg / 1000;
                printf("i: %d : %d : Temp: %f\t\n",i, fibonaci(i), temp);
        }
        fclose(fp2);
        return 0;
}

demo17.c

#include <stdio.h>
int main(int argc, char *argv[])
{
        if( argc == 2)
        {
                printf("The argument supplied is %s\n", argv[1]);
        }
        else if (argc > 2)
        {
                printf("Too many arguments supplied.\n");
        }
        else
        {
                printf("One argument expected.\n");
        }
}

demo18.c

#include <stdio.h>
void bubble_sort(int arr[],int len)
{
        int i, j, temp;
        for ( i = 0; i < len - 1; i++)
           for ( j=0; j < len - 1 - i; j++)
                   if ( arr[j] > arr[ j + 1 ])
                   {
                           temp = arr[j];
                           arr[j] = arr[j+1];
                           arr[j +1 ] = temp;
                   }
}

int main()
{
        int arr[] = { 22, 34, 3, 32, 82, 55,89, 50 ,34,37, 5, 65, 64, 35, 9 ,70};
        int len = (int) sizeof(arr) / sizeof(*arr);
        bubble_sort(arr, len);
        int i;
        for (i = 0; i < len; i++)
                printf("%d ", arr[i]);
                printf("\n");
        return 0;
}

demo19.c

#include <stdio.h>
void swap(int *a, int *b)
{
   int temp =  *a;
   *a = *b;
   *b = temp;
}

void selection_sort(int arr[], int len)
{
        int i,j;
        for ( i = 0; i < len - 1; i++ )
        {
                int min = i;
                for ( j = i + 1 ; j < len ; j++)
                        if ( arr[j] < arr[min])
                                min = j;
                swap(&arr[min], &arr[i]);
        }
}

int main()
{
        int arr[] = { 22, 34, 3, 32, 82, 55,89, 50 ,34,37, 5, 65, 64, 35, 9 ,70};
        int len = (int) sizeof(arr) / sizeof(*arr);
//      bubble_sort(arr, len);
        selection_sort(arr, len);
        int i;
        for (i = 0; i < len; i++)
                printf("%d ", arr[i]);
                printf("\n");
        return 0;
}

好了,就先来点儿基础的热热身。

树莓派串口驱动的情况

树莓派串口驱动详细

串口驱动现状

本来在树莓派上插入了一个sim800c的设备,但是这个产品带着一颗ch3401的芯片,在设备上用ls /dev/ttyUSB*竟然没有找到串口设备,内心想可能是没有驱动,于是到官方站点上下载了一下。

看更新时间是2018年3月,然后打开压缩包。

然后发现Readme里面已经告诉我们支持的内核只能是:

太老了。后来查资料发现好像这几款常见芯片已经被加入到Linux内核,早已经支持。抱着怀疑的态度查看了一下。

果然都支持了。
包括ch341, cp210x系列,pl2303, ftdi, 好吧,这下方便多了,以后在linux下做串口设备的调试就不要担心串口芯片不兼容了!
然后再通过lsusb和lsmod还有dmesg检查后发现,已经识别了。。

检查看看串口是否连上来出现一个/dev/ttyUSB0的设备:

这样才对么。我下面就可以用串口来获取一下sim800C的sim卡联网的状态信息了。

测试代码:

#!/usr/bin/env python3
import serial
import time
import operator
import os

time.sleep(2)
ser = serial.Serial('/dev/ttyUSB0', 115200)
print("串口初始化完成...")

if ser.isOpen == False:
    ser.open()
try:
    print('-'*60)
    print("初始化SIM800C")
    print("尝试测试SIM800C联网获取CCID信息...")
    time.sleep(2)
    i = 0
    while True:
        ser.write(str.encode("AT+CCID\r"))
        size = ser.inWaiting()
        if size != 0:
            response = ser.read(size)
            ccid = str(response,encoding="utf8")
            print(ccid)
        ser.write(str.encode("AT+CGMR\r"))
        size = ser.inWaiting()
        if size != 0:
            connection = ser.read(size)
            creg = str(connection, encoding="utf8")
            print(creg)
            time.sleep(1)
        ser.write(str.encode("AT+CSQ\r"))
        size = ser.inWaiting()
        if size != 0:
            csq = ser.read(size)
            csqstatus = str(csq, encoding="utf8")
            print(csqstatus)
            time.sleep(1)
        ser.write(str.encode("AT+CGACT=1\r"))
        size = ser.inWaiting()
        if size != 0:
            cgact = ser.read(size)
            cgactstatus = str(cgact, encoding="utf8")
            print(cgactstatus)
        else:
            ser.flushInput()
            time.sleep(1)
except KeyboardInterrupt:
    ser.close()

结果

今天就到这里,白了个白~