24 / 07 / 10

「一生一芯」Learn C the hard way - Ex 6

练习 6:变量类型

include <stdio.h> int main(int argc, char *argv[]) { int distance = 100; float power = 2.345f; double super_power = 56789.4532; char initial = 'A'; char first_name[] = "Zed"; char last_name[] = "Shaw"; printf("You are %d miles away.\n", distance); printf("You have %f levels of power.\n", power); printf("You have %f awesome super powers.\n", super_power); printf("I have an initial %c.\n", initial); printf("I have a first name %s.\n", first_name); printf("I have a last name %s.\n", last_name); printf("My whole name is %s %c. %s.\n", first_name, initial, last_name); return 0; }

附加题 1

寻找其他通过修改printf使这段C代码崩溃的方法。

#include <stdio.h> int main(int argc, char *argv[]) { int distance = 100; float power = 2.345f; double super_power = 56789.4532; char initial = 'A'; char first_name[] = "Zed"; char last_name[] = "Shaw"; // Incorrect format specifiers: printf("You are %f miles away.\n", distance); // should be %d printf("You have %d levels of power.\n", power); // should be %f printf("You have %s awesome super powers.\n", super_power); // should be %f printf("I have an initial %s.\n", initial); // should be %c printf("I have a first name %d.\n", first_name); // should be %s printf("I have a last name %f.\n", last_name); // should be %s printf("My whole name is %s %d. %c.\n", first_name, initial, last_name); // %d and %c should be swapped return 0; }

附加题 2

搜索“printf格式化”,试着使用一些高级的占位符。

看看练习 3 呢。

附加题 3

研究可以用几种方法打印数字。尝试以八进制或十六进制打印,或者其它你找到的方法。

#include <stdio.h> int main() { int number = 255; float power = 123.456f; // 打印整数 printf("Decimal: %d\n", number); printf("Octal: %o\n", number); printf("Hexadecimal (lowercase): %x\n", number); printf("Hexadecimal (uppercase): %X\n", number); printf("Unsigned Decimal: %u\n", number); // 打印浮点数 printf("Default format: %f\n", power); printf("Scientific notation: %e\n", power); printf("Shortest representation: %g\n", power); // 打印带有精度控制的浮点数 printf("Two decimal places: %.2f\n", power); printf("Four decimal places: %.4f\n", power); printf("Scientific notation with two significant figures: %.2e\n", power); printf("Shortest representation with four significant figures: %.4g\n", power); return 0; }

附加题 4

试着打印空字符串,即""。

#include <stdio.h> int main() { // 打印空字符串 printf("This is an empty string: \"%s\"\n", ""); // 打印空字符串在其他字符串的上下文中 char empty_string[] = ""; printf("Here is another empty string: \"%s\"\n", empty_string); return 0; }