《C++ Primer Plus(第六版)》(1)(第二章 开始学习C++ 笔记和答案)
写在某天:真是日了狗了,看了这么多才发现C++ Primer 和 C++ Primer Plus是不同的书,原来外国人也会山寨的。
大学的时候都是学Java的,毕业这么多年好像都没有系统学过C++,现在决定过一遍。
笔记的话只记录我觉得自己之前不是很清楚的部分。
题目则全部做一遍。
头文件:
C++旧式风格:以.h结尾,例如iostream.h
C旧式风格:以.h结尾,例如math.h
C++新式风格:没有扩展名,例如iostream
转换后的C:加上前缀c,没有扩展名,例如cmath
小结一下:
1、C++官方明确反对旧式的C++风格,C的没有明确反对。
2、在某一个编译器内,可能会同时支持iostream.h,iostream,ciostream等文件,但是这是不同的文件来的,对于一般用户来说,这些是无关紧要的。但是函数内部实现不同,所以尽量用新的。
3、.h文件在编译的时候,是复制到cpp文件里面的,所以.h文件是不能独立编译的,引入太多.h文件应该也会造成程序太大吧。
4、新的头文件里面使用了std域名,怪不得以前上课的时候,书本的例子都是没有std的,原来是太旧了。
看完顺便做一下题目吧:
main.cpp
#include <iostream> #include "Chapter2.h" int main() { CChapter2Answer::answer();//第二章答案 return 0; }Chapter2.h
#ifndef _Cpp_Primer_Chapter2_H_ #define _Cpp_Primer_Chapter2_H_ class CChapter2Answer { public: static void answer(); }; #endifChapter2.cpp
#include "Chapter2.h" #include <iostream> #include <string> using namespace std; int a_2(int a) { return a * 220; } void a_3_1() { std::cout << "Three blind mice" << std::endl; } void a_3_2() { std::cout << "See how they run" << std::endl; } void a_4() { //输入年龄,输出月份数 int age = 0; std::cout << "Please enter your age:" << endl; std::cin >> age; std::cout << "has " << age * 12 << " mount." << endl; } void a_5( ) { std::cout << "Please enter a Celsius value: " << std::endl; double t = 0; std::cin >> t; std::cout<< t << " degrees Celsius is "<< t * 1.8 + 32 << " degrees Fahrenheit" << std::endl; } void a_6() { std::cout << "Please enter the number of light years: " << std::endl; double t = 0; std::cin >> t; std::cout << t << " light years = " << t * 63240 << " astronomical units" << std::endl; } void a_7(int hours, int minutes) { std::cout << "Time: " << hours << ":" << minutes; } void CChapter2Answer::answer() { //第二章 //2.6 复习题 // 1.函数 // 2.在最终的编译之前,使用iostream文件的内容替换该编译指令。 // 3.使程序可以使用std命名空间中的定义 // 4. cout << "Hello, World" << endl; //or cout << "Hello, World\n"; // 5. int cheeses; // 6. cheeses = 32; // 7. std::cin >> cheeses; // 8. cout << "We have " << cheeses<< " varieties of cheeses" << endl; // 9. int froop(double t);//输入double,返回int void rattle(int n);//输入int,无返回 int prune(void);//无输入,返回int // 10.例如: void rattle(int n); // 函数声明返回void,而且在函数末尾已经无其他代码,则可不写return // 11.问题的描述本身就有问题,错误原因未知,不是怎么修复,而是可能是什么原因。 // (1)未引入iostream头文件 // (2)已经引入头文件,但是没有写名使用std命名空间,using namespace std; // (3)已经引入头文件,使用的时候直接写std::cout<<"xxx"<<std::endl; //2.7 编程练习 // 1. std::string name = "FableGame"; std::string adress = "http://blog.csdn.net/u012175089"; std::cout << "name : " << name << std::endl; std::cout << "adress : " << adress << std::endl; // 2.日了狗了,我居然不知道这个long是什么单位 int ma = a_2(123); // 3. a_3_1(); a_3_2(); // 4.输入年龄,输出月份数 a_4(); // 5. a_5(); // 6. a_6(); // 7. int hours = 0; int minutes = 0; std::cout << "Please enter the number of hours: "; cin >> hours; std::cout << "Please enter the number of minutes: "; cin >> minutes; a_7(hours, minutes); }
人生如戏,还是戏如人生?微信公众号:传说之路
csdn博客 http://blog.csdn.net/u012175089/article/list/2