Fork me on GitHub

C 程序入门(二)

1, 入门程序

  • 创建hello.c文件,并将下方代码粘贴;
  • 使用gcc hello.c -o hello编译该文件;
  • 运行:./hello
#include <stdio.h>

int main()
{
    printf("Hello World!\n");

    return 0;
}

2, 变量

#include <stdio.h>

int main()
{
    int price = 0;
    printf("请输入金额(元):");
    scanf("%d", &price);

    int change = 100 - price;

    printf("找您%d 元。\n", change);
}

3, C 语言练习题

#include <stdio.h>

// 02-1 厘米换算英尺英寸
// 米 = (foot + inch/12) * 0.3048

int main()
{
    int x;
    printf("请输入一个整数(厘米):");
    scanf("%d", &x);
    double total = x / 100.0 / 0.3048;
    int foot = total;
    int inch = (total - foot) * 12.0;
    printf("foot: %d, inch: %d", foot, inch);

}

// 02-2 然后是几点
int time_caculate()
{
    int start,step;
    printf("请输入两个整数:");
    scanf("%d %d", &start, &step);
    // 待增加 minutes
    int minutes = step % 60;
    int startMin = start % 100;
    int endMin = minutes + startMin;
    int gapHour = 0;
    int resultMin = 0;
    if (endMin > 60) {
        gapHour = endMin / 60;
        resultMin = endMin % 60;
    } else {
        resultMin = endMin;
    }
    // 待增加 hour
    int hour = step / 60;
    // 最终结果
    int end = (start / 100 + hour + gapHour)* 100 + resultMin;
    
    printf("终止时间:%d\n", end);
}

4. 数据类型

  • 整数
    • char,short,int,long,long long
  • 浮点数
    • float,double,long double
  • 布尔值
    • bool
  • 指针: 保存地址的变量
  • 自定义类型
  • sizeof(): 给出某个类型或变量在内存中所占据的字节数;
// 负数如何表达?
// 参考链接:https://www.bilibili.com/video/BV19W411B7w1?p=57
#include <stdio.h>

int main()
{
    char c = 255;
    int i = 255;
    printf("c=%d, i=%d\n", c, i);
    return 0;
}

// inf 和 nan
#include <stdio.h>

int main()
{
    printf("%f\n", 12.0/0.0);
    printf("%f\n", -12.0/0.0);
    printf("%f\n", 0.0/0.0);

    return 0;
}


// 数组地址
#include <stdio.h>

int main(void)
{
    int a[10];

    printf("%p\n", &a);
    printf("%p\n", a);
    printf("%p\n", &a[0]);
    printf("%p\n", &a[1]);

    return 0;
}


// 指针运算:
// 参考地址: https://www.bilibili.com/video/BV19W411B7w1?p=87
#include <stdio.h>

int main(void)
{
    char ac[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9,};
    char *p = ac;
    
    printf("p = %p\n", p);
    printf("p+1 = %p\n", p+1);
    
    int ai[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9,};
    int *q = ai;
    printf("q = %p\n", q);
    printf("q+1 = %p\n", q+1);

    return 0;
}

参考资料:

posted @ 2019-12-17 21:00  小a的软件思考  阅读(227)  评论(0编辑  收藏  举报