变量与基本数据类型
从基础开始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);
}