第一章
1.3
//1.3
#include <iostream>
using namespace std;
int main() {
std::cout << "Hello, World!" << endl;
return 0;
}
1.4
//1.4
#include <iostream>
using namespace std;
int main() {
std::cout << "Enter two numbers:" << std::endl;
int v1 = 0, v2 = 0;
std::cin >> v1 >> v2;
std::cout << "The sum of " << v1 << " and " << v2
<< " is " << v1 + v2 << std::endl;
std::cout << "The mul of " << v1 << " and " << v2
<< " is " << v1 * v2 << std::endl;
return 0;
}
1.5
//1.5
#include <iostream>
using namespace std;
int main() {
std::cout << "Enter two numbers:" << std::endl;
int v1 = 0, v2 = 0;
std::cin >> v1 >> v2;
std::cout << "The sum of ";
std::cout << v1;
std::cout << " and ";
std::cout << v2;
std::cout << " is ";
std::cout << v1 + v2;
std::cout << std::endl;
std::cout << "The mul of ";
std::cout << v1;
std::cout << " and ";
std::cout << v2;
std::cout << " is ";
std::cout << v1 * v2;
std::cout << std::endl;
return 0;
}
1.6:解釋下面程序片段是否合法
std::cout << "The sum of " << v1;
<< " and " << v2;
<< " is " << v1 + v2 << std::endl;
?如果程序是合法的站绪,它會(huì)輸出什么爬坑?
The sum of v1
?如果程序不合法吱殉,原因何在忧陪?
' ; '代表了程序的一條語句的結(jié)束,剩下的語句不知道寫入哪一個(gè)ostream對(duì)象當(dāng)中
<< " and " << v2;
<< " is " << v1 + v2 << std::endl;
?應(yīng)該如何修正浆洗?
std::cout << "The sum of " << v1;
std::cout << " and " << v2;
std::cout << " is " << v1 + v2 << std::endl;
1.3節(jié)練習(xí)
1.7 編譯一個(gè)包含不正確的嵌套注釋的程序催束,觀察編譯器返回的錯(cuò)誤信息
代碼
#include <iostream>
using namespace std;
/*
* 注釋對(duì)/* */不能嵌套
* "不能嵌套"幾個(gè)字會(huì)被認(rèn)為是源碼
* 像剩余程序一樣處理
*/
int main() {
return 0;
}
錯(cuò)誤信息:
main.cpp:7:13: warning: '/*' within block comment [-Wcomment]
* 注釋對(duì)/* */不能嵌套
^
main.cpp:7:18: error: unknown type name '不能嵌套'
* 注釋對(duì)/* */不能嵌套
^
main.cpp:8:4: error: expected unqualified-id
* "不能嵌套"幾個(gè)字會(huì)被認(rèn)為是源碼
^
1 warning and 2 errors generated.
make[3]: *** [CMakeFiles/C___Primer.dir/main.cpp.o] Error 1
make[2]: *** [CMakeFiles/C___Primer.dir/all] Error 2
make[1]: *** [CMakeFiles/C___Primer.dir/rule] Error 2
make: *** [C___Primer] Error 2
1.8 指出下列哪些輸出語句是合法的(如果有的話):
std::cout << "/*";
std::cout << "*/";
std::cout << /* "*/" */;
std::cout << /* "*/" /* "/*" */;
預(yù)測(cè)編譯這些語句會(huì)產(chǎn)生什么樣的結(jié)果,實(shí)際編譯這些語句來驗(yàn)證你的答案(編寫一個(gè)小程序辅髓,每次將上述一條語句作為其主體)泣崩,改正每個(gè)編譯錯(cuò)誤
std::cout << "/*"; 輸出:/*
std::cout << "*/"; 輸出:*/
std::cout << /* "*/" */; 報(bào)錯(cuò)
std::cout << /* "*/" /* "/*" */; 輸出:/*
報(bào)錯(cuò)信息 及 代碼
錯(cuò)誤代碼:
std::cout << /* "*/" */;
報(bào)錯(cuò)信息:
main.cpp:8:24: warning: missing terminating '"' character [-Winvalid-pp-token]
std::cout << /* "*/" */;
^
main.cpp:8:24: error: expected expression
1 warning and 1 error generated.
更正代碼
std::cout << /* "*/" */"; 輸出*/