三、数据和C
4. C语言基本数据类型
4.7 复数与虚数类型
3种复数类型:float_Complex、double_Complex、和long double_Comlex
3种虚数类型:float_Imaginary、doube_Imaginary和long double_Imaginary。
4.8 其他类型
数组、指针、结构和联合
4.9 类型大小
/* typesize.c -- 打印类型大小 */
#include <stdio.h>
int main(void)
{
/* C99为类型大小提供%zd转换说明*/
printf("Type int has a size of %zd bytes.\n", sizeof(int));
printf("Type char has a size of %zd bytes.\n", sizeof(char));
printf("Type long has a size of %zd bytes.\n", sizeof(long));
printf("Type long long has a size of %zd bytes.\n", sizeof(long long));
printf("Type double has a size of %zd bytes.\n", sizeof(double));
printf("Type long double has a size of %zd bytes.\n",sizeof(long double));
return 0;
}
//Type int has a size of 4 bytes.
//Type char has a size of 1 bytes.
//Type long has a size of 8 bytes.
//Type long long has a size of 8 bytes.
//Type double has a size of 8 bytes.
//Type long double has a size of 16 bytes.
5. 使用数据类型
int apples = 3; /* 正确 */
int oranges = 3.0; /* 不好的形式 */
int cost = 12.99 /* 用double类型的值初始化int类型的变量 */
float pi = 3.1415926536; /* 用double类型的值初始化float 类型的变量*/
5. 参数和陷阱
/* badcout.c -- 参数错误的情况 */
#include <stdio.h>
int main(void)
{
int n = 4;
int m = 5;
float f = 7.0f;
float g = 8.0f;
printf("%d\n", n, m); /* 参数太多 */
printf("%d %d %d\n", n);/* 参数太少 */
printf("%d %d \n", f, g);/* 值的类型不匹配*/
return 0;
}
//XCode 4.6 (OS 10.8)的输出如下:
//4
//4 1 706337836
//1606414344 1
//Microsoft Visual Studio Express 2012 (Windows 7) 的输出如下:
//4
//4 0 0
//0 1075576832
6. 转义序列示例
/* escape.c -- 使用转移序列 */
#include <stdio.h>
int main(void)
{
float salary;
printf("\aEnter your desired monthly salary:"); /* 1 */
pritnf("$__________\b\b\b\b\b\b\b"); /* 2 */
scanf("%f", &salary);
printf("\n\t$%.2f a month is $%.2f a year.", salary,
salary * 12.0); /* 3 */
printf("\rGee!\n");
return 0;
}
7. 程序运行情况
■刷新输出
四、字符串和格式化输入/输出
1.前导程序
// talkback.c -- 演示与用户交互
#include <stdio.h>
#include <string.h> // 提供 strlen()函数的原型
#define DENSITY 62.4 // 人体密度(单位:磅/立方英尺)
int main()
{
float weight, volume;
int size, letters;
char name[40]; // name是一个可容纳40个字符的数组
printf("Hi! What's your first name?\n");
scanf("%s, name");
printf("%s, what's your weight in pounds?\n", name);
scanf("%f", &weight);
size = sizeof(name);
letters = strlen(name);
volume = weight / DENSITY;
printf("Well, %s, your volume is %2.2f cubic feet.\n", name, volume);
printf("Also, your first name has %d letters,\n", letters);
pritnf("and we have %d bytes to store it.\n", size);
return 0;
}