C语言变量与基本数据类型

本文介绍了C语言的基础知识,包括变量的声明与初始化,如整型(int)、字符型(char)和浮点型(float),以及数组的使用。文章还详细讲解了格式化输出函数printf,如%d用于整型,%c用于字符,%s用于字符串,%f用于浮点数。此外,还提到了常量的概念,常量的值在程序执行中不可更改。
摘要由CSDN通过智能技术生成

变量与基本数据类型

从基础开始c语言。

#include <stdio.h>

int main() {

    int age = 21; // 定义 + 初始化
    char grade = 'A'; // single character
    char name[] = "xielinfeng"; // array of characters
    float gpa = 3.8;


    printf("Hello %s\n", name); // s stands for string 
    printf("You are %d years old\n", age); // %d中的d表示十进制( decimal )
    printf("Your average grade is %c\n", grade); // c stands for char
    printf("Your gpa is %f\n", gpa); // f stands for float


    /*
        char can store a number range from -128 ~ 127  
        unsign char can store a number range from 0 ~ 255
        To display , you can use %d or %c
    */
    char f = 'a';  
    unsigned char g = 255;
    printf("%d\n", f); 
    printf("%d\n", g);


    return 0;
}

c format specifier :%

#include <stdio.h>

int main() {
    /*
        format specifier % 
        define and format a type of data to be display

        %c = character
        %d = integer (decimal)
        %s = string 
        %f = float 
        %lf = double (long float)

        %.1 = 小数点后保留一位数字
        %8 = minimum field width
        %- = left align

    */

   float item1 = 5.75;
   float item2 = 10.00;
   float item3 = 10.99;

    // 展示结果为: 每个数左对齐,长度为8,小数点后保留两位
   printf("item 1 : $%-8.2f\n", item1);
   printf("item 2 : $%-8.2f\n", item2);
   printf("item 3 : $%-8.2f\n", item3);

}

常量

常量在程序执行过程中不能被修改,否则会报错

#include <stdio.h>

int main() {

    // constant : fixed value that cannot be altered by the program

    const float PI = 3.1415;

    // any attempt to change the value of PI would cause an error

    printf("%.4f", PI);

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值