prog1.cc 文件代碼:ios
int main() { return 0; }
在prog1.cc 文件所在目錄下,依次執行下面命令:程序員
➜ Desktop CC prog1.cc ➜ Desktop a.out ➜ Desktop echo $? 0
注:這裏prog1.cc 文件所在目錄爲Desktop;shell
prog1.cc 文件代碼修改成:express
int main() { return -1; }
在prog1.cc 文件所在目錄下,依次執行下面命令:ide
➜ Desktop CC prog1.cc ➜ Desktop a.out ➜ Desktop echo $? 255
注:這裏prog1.cc 文件所在目錄爲Desktop;post
#include <iostream> int main() { std::cout << "Hello, World" << std::endl; return 0; }
#include <iostream> int main() { std::cout << "Enter two numbers:" << std::endl; int v1 = 0, v2 = 0; std::cin >> v1 >> v2; std::cout << "The product of " << v1 << " and " << v2 << " is " << v1 * v2 << std::endl; return 0; }
#include <iostream> int main() { std::cout << "Enter two numbers:"; std::cout << 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; return 0; }
std::cout << "The sum of " << v1; << " and " << v2; << " is " << v1 + v2 << std::endl;
不合法,分號表示一個語句的結束。修正方法:測試
方法一:ui
std::cout << "The sum of " << v1; std::cout << " and " << v2; std::cout << " is " << v1 + v2 << std::endl;
方法二:this
std::cout << "The sum of " << v1 << " and " << v2 << " is " << v1 + v2 << std::endl;
#include <iostream> /* * 註釋對/* */不能嵌套。 * "不能嵌套"幾個字會被認爲是源碼, * 像剩餘程序同樣處理 */ int main() { return 0; }
std::cout << "/*"; // 合法,輸出:/* std::cout << "*/"; // 合法,輸出:*/ std::cout << /* "*/" */; // 不合法 // 編譯器提示warning: missing terminating '"' character // 編譯器把第一對/* "*/識別爲註釋界定符;剩餘的" */;識別爲源碼。 std::cout << /* "*/" /* "/*" */; // 合法,輸出 /* // 首(/* "*/)尾(/*" */)爲界定符;" /* "爲源碼 // /* "*/" /* "/*" */整個這句的一開始是界定符/*,編譯器把和它匹配的最近*/之間的內 // 容( ")識別爲註釋;接着是",標誌着下一個和它匹配的最近"之間的內容( /* )是字符 // 串;接着是界定符/*,編譯器把和它匹配的最近*/之間的內容(" )識別爲註釋。 // 原則:從左往右,就近匹配。
#include <iostream> int main() { int sum = 0, val = 50; while (val <= 100) { sum += val; ++val; } std::cout << "Sum of 50 to 100 inclusive is " << sum << std::endl; return 0; }
#include <iostream> int main() { int val = 10; while (val >= 0) { std::cout << val << " "; --val; } std::cout << std::endl; return 0; }
#include <iostream> int main() { int val1, val2, temp; std::cout << "Please input two integers"; std::cin >> val1 >> val2; if (val1 > val2) { temp = val1; val1 = val2; val2 = temp; } ++val1; while (val1 < val2) { std::cout << val1 << " "; ++val1; } std::cout << std::endl; return 0; }
#include <iostream> int main() { int sum = 0; // for循環完成-100~+100之間全部整數累加求和 for (int i = -100; i <= 100; ++i) sum += i; std::cout << sum << std::endl; return 0; }
sum的終值是0spa
#include <iostream> int main() { int sum = 0; for (int val = 50; val <= 100; ++val) sum += val; std::cout << "Sum of 50 to 100 inclusive is " << sum << std::endl; return 0; }
#include <iostream> int main() { for (int val = 10; val >= 0; --val) std::cout << val << " "; std::cout << std::endl; return 0; }
#include <iostream> int main() { int val1, val2, temp; std::cout << "Please input two integers"; std::cin >> val1 >> val2; if (val1 > val2) { temp = val1; val1 = val2; val2 = temp; } for (++val1; val1 < val2; ++val1) std::cout << val1 << " "; std::cout << std::endl; return 0; }
while (condition) statement
while 循環的條件判斷(condition)語句在每次執行完循環體(statement)語句都會執行,判斷是否繼續執行循環體。
for (init-statement; condition; expression) statement
for 循環的初始化語句(init-statement)在循環開始的時候執行一次,以後執行判斷語句(condition),若知足條件,則執行循環體(statement),循環體內的語句執行完後緊接着執行表達式(expression),表達式的做用通常是做用判斷語句(condition),使循環在有限次內結束,而不是無限循環。固然 init-statement、conditon和expression這三條語句也能夠爲空語句(分號不能夠省略):
for (;;) statement
也能夠寫多條,多條之間用逗號分隔:
#include <iostream> int main() { for (int i = 0, j = 0; i < 2, j < 2; ++i, ++j) std::cout << i << " " << j << '\n'; std::cout << std::endl; return 0; }
while 循環的優勢是書寫簡單,缺點是程序員可能忘記在循環體(statement)內做用條件判斷語句(condition),形成無限循環;for 循環的優勢是規範、整潔,不易漏掉做用條件判斷(condition)的表達式(expression),缺點是書寫稍繁瑣。while 循環適合循環次數不肯定的情景;for 循環適合循環次數事先已知。
略
#include <iostream> int main() { int sum = 0, value = 0; while (std::cin >> value) { sum += value; } std::cout << "Sum is: " << sum << std::endl; return 0; }
若是輸入的值都相等,程序輸出相等值的個數;若是沒有重複值程序則輸出每一個數字出現次數爲1,按一次Enter
,輸出上一個數字的統計結果爲1.
// 測試數據 3 3 3 3 4 // 運行結果 3 occurs 4 times // 測試數據 5 // 運行結果 4 occurs 1 times // 測試數據 6 // 運行結果 5 occurs 1 times // 測試數據 7 // 運行結果 6 occurs 1 times // 測試數據 8 // 運行結果 7 occurs 1 times
// 測試數據 100 100 100 100 100 100 1 2 3 4 5 6 7 8 // 運行結果 100 occurs 6 times 1 occurs 1 times 2 occurs 1 times 3 occurs 1 times 4 occurs 1 times 5 occurs 1 times 6 occurs 1 times 7 occurs 1 times
1.11 已經考慮到該狀況。
C++ Primer 5th source code download
Sales_item.h
/* * This file contains code from "C++ Primer, Fifth Edition", by Stanley B. * Lippman, Josee Lajoie, and Barbara E. Moo, and is covered under the * copyright and warranty notices given in that book: * * "Copyright (c) 2013 by Objectwrite, Inc., Josee Lajoie, and Barbara E. Moo." * * * "The authors and publisher have taken care in the preparation of this book, * but make no expressed or implied warranty of any kind and assume no * responsibility for errors or omissions. No liability is assumed for * incidental or consequential damages in connection with or arising out of the * use of the information or programs contained herein." * * Permission is granted for this code to be used for educational purposes in * association with the book, given proper citation if and when posted or * reproduced.Any commercial use of this code requires the explicit written * permission of the publisher, Addison-Wesley Professional, a division of * Pearson Education, Inc. Send your request for permission, stating clearly * what code you would like to use, and in what specific way, to the following * address: * * Pearson Education, Inc. * Rights and Permissions Department * One Lake Street * Upper Saddle River, NJ 07458 * Fax: (201) 236-3290 */ /* This file defines the Sales_item class used in chapter 1. * The code used in this file will be explained in * Chapter 7 (Classes) and Chapter 14 (Overloaded Operators) * Readers shouldn't try to understand the code in this file * until they have read those chapters. */ #ifndef SALESITEM_H // we're here only if SALESITEM_H has not yet been defined #define SALESITEM_H // Definition of Sales_item class and related functions goes here #include <iostream> #include <string> class Sales_item { // these declarations are explained section 7.2.1, p. 270 // and in chapter 14, pages 557, 558, 561 friend std::istream& operator>>(std::istream&, Sales_item&); friend std::ostream& operator<<(std::ostream&, const Sales_item&); friend bool operator<(const Sales_item&, const Sales_item&); friend bool operator==(const Sales_item&, const Sales_item&); public: // constructors are explained in section 7.1.4, pages 262 - 265 // default constructor needed to initialize members of built-in type Sales_item(): units_sold(0), revenue(0.0) { } Sales_item(const std::string &book): bookNo(book), units_sold(0), revenue(0.0) { } Sales_item(std::istream &is) { is >> *this; } public: // operations on Sales_item objects // member binary operator: left-hand operand bound to implicit this pointer Sales_item& operator+=(const Sales_item&); // operations on Sales_item objects std::string isbn() const { return bookNo; } double avg_price() const; // private members as before private: std::string bookNo; // implicitly initialized to the empty string unsigned units_sold; double revenue; }; // used in chapter 10 inline bool compareIsbn(const Sales_item &lhs, const Sales_item &rhs) { return lhs.isbn() == rhs.isbn(); } // nonmember binary operator: must declare a parameter for each operand Sales_item operator+(const Sales_item&, const Sales_item&); inline bool operator==(const Sales_item &lhs, const Sales_item &rhs) { // must be made a friend of Sales_item return lhs.units_sold == rhs.units_sold && lhs.revenue == rhs.revenue && lhs.isbn() == rhs.isbn(); } inline bool operator!=(const Sales_item &lhs, const Sales_item &rhs) { return !(lhs == rhs); // != defined in terms of operator== } // assumes that both objects refer to the same ISBN Sales_item& Sales_item::operator+=(const Sales_item& rhs) { units_sold += rhs.units_sold; revenue += rhs.revenue; return *this; } // assumes that both objects refer to the same ISBN Sales_item operator+(const Sales_item& lhs, const Sales_item& rhs) { Sales_item ret(lhs); // copy (|lhs|) into a local object that we'll return ret += rhs; // add in the contents of (|rhs|) return ret; // return (|ret|) by value } std::istream& operator>>(std::istream& in, Sales_item& s) { double price; in >> s.bookNo >> s.units_sold >> price; // check that the inputs succeeded if (in) s.revenue = s.units_sold * price; else s = Sales_item(); // input failed: reset object to default state return in; } std::ostream& operator<<(std::ostream& out, const Sales_item& s) { out << s.isbn() << " " << s.units_sold << " " << s.revenue << " " << s.avg_price(); return out; } double Sales_item::avg_price() const { if (units_sold) return revenue/units_sold; else return 0; } #endif
main.cpp
#include <iostream> #include "Sales_item.h" int main() { Sales_item book; // 讀入 ISBN 號、售出的冊數以及銷售價格 std::cin >> book; // 寫入 ISBN、售出的冊數、總銷售額和平均價格 std::cout << book << std::endl; return 0; }
Clion IDE :
// 測試數據 0-201-70353-X 4 24.99 // 運行結果 0-201-70353-X 4 99.96 24.99 Process finished with exit code 0
Sales_item.h 同1.20,main.cpp 內容以下:
#include <iostream> #include "Sales_item.h" int main() { Sales_item item1, item2; std::cin >> item1 >> item2; // 讀取一對交易記錄 std::cout << item1 + item2 << std::endl; // 打印它們的和 return 0; }
Clion IDE :
// 測試數據 0-201-78345-X 3 20.00 0-201-78456-X 2 25.00 // 運行結果 0-201-78345-X 5 110 22 Process finished with exit code 0
Sales_item.h 同1.20,main.cpp 內容以下:
/* * This file contains code from "C++ Primer, Fifth Edition", by Stanley B. * Lippman, Josee Lajoie, and Barbara E. Moo, and is covered under the * copyright and warranty notices given in that book: * * "Copyright (c) 2013 by Objectwrite, Inc., Josee Lajoie, and Barbara E. Moo." * * * "The authors and publisher have taken care in the preparation of this book, * but make no expressed or implied warranty of any kind and assume no * responsibility for errors or omissions. No liability is assumed for * incidental or consequential damages in connection with or arising out of the * use of the information or programs contained herein." * * Permission is granted for this code to be used for educational purposes in * association with the book, given proper citation if and when posted or * reproduced.Any commercial use of this code requires the explicit written * permission of the publisher, Addison-Wesley Professional, a division of * Pearson Education, Inc. Send your request for permission, stating clearly * what code you would like to use, and in what specific way, to the following * address: * * Pearson Education, Inc. * Rights and Permissions Department * One Lake Street * Upper Saddle River, NJ 07458 * Fax: (201) 236-3290 */ #include <iostream> #include "Sales_item.h" int main() { Sales_item item1, item2; std::cin >> item1 >> item2; // first check that item1 and item2 represent the same book if (item1.isbn() == item2.isbn()) { std::cout << item1 + item2 << std::endl; return 0; // indicate success } else { std::cerr << "Data must refer to same ISBN" << std::endl; return -1; // indicate failure } }
Clion IDE :
// 測試數據1 0-201-78345-X 4 20.00 0-201-78345-X 5 20.00 // 運行結果1 0-201-78345-X 9 195 21.6667 Process finished with exit code 0 // 測試數據2 0-202-78222-Y 2 25.00 0-201-78111-X 2 29.00 // 運行結果2 Data must refer to same ISBN Process finished with exit code 255
注:程序結束 0 和 255 正好分別對應 return 0 和 return -1.
#include <iostream> #include "Sales_item.h" int main() { Sales_item currItem, valItem; if (std::cin >> currItem) { int cnt = 1; while (std::cin >> valItem) { if (valItem.isbn() == currItem.isbn()) { ++cnt; } else { std::cout << currItem.isbn() << " occurs " << cnt << " times " << std::endl; currItem = valItem; cnt = 1; } } std::cout << currItem.isbn() << " occurs " << cnt << " times " << std::endl; } return 0; }
// 測試數據 0-201-78345-X 4 25.0 0-201-78345-X 1 25.0 0-201-78345-X 2 25.0 0-201-78345-X 9 25.0 0-207-78345-X 9 31.0 0-207-78345-X 3 31.0 0-202-78345-X 3 20.0 0-202-78345-X 3 20.0 // 運行結果 0-201-78345-X occurs 4 times 0-207-78345-X occurs 2 times // 接着仍能夠繼續輸入測試數據
將 exercise_23.cpp 編譯運行(代碼如 1.23),生成可執行程序。
在控制檯執行:
Last login: Wed May 29 08:17:52 on console ➜ ~ /Users/xxx/Desktop/exercise_23 </Users/xxx/Desktop/Untitled-1 >/Users/xxx/Desktop/Untitled-2 ➜ ~
Untitled-1 文檔內容爲:
0-201-78345-X 4 25.0 0-201-78345-X 1 25.0 0-201-78345-X 2 25.0 0-201-78345-X 9 25.0 0-207-78345-X 9 31.0 0-207-78345-X 3 31.0 0-202-78345-X 3 20.0 0-202-78345-X 3 20.0
Untitled-2 文檔內容爲:
0-201-78345-X occurs 4 times 0-207-78345-X occurs 2 times 0-202-78345-X occurs 2 times
注:該題考查書中知識點使用文件重定向\(P_{19}\)
Sales_item.h 同1.20,main.cpp 內容以下:
#include <iostream> #include "Sales_item.h" int main() { Sales_item total; // 保存下一條交易記錄的變量 // 讀入第一條交易記錄,並確保有數據能夠處理 if (std::cin >> total) { Sales_item trans; // 保存和的變量 // 讀入並處理剩餘交易記錄 while (std::cin >> trans) { // 若是咱們仍在處理相同的書 if (total.isbn() == trans.isbn()) total += trans; // 更新總銷售額 else { // 打印前一本書的結果 std::cout << total << std::endl; total = trans; // total 如今表示下一本書的銷售額 } } std::cout << total << std::endl; // 打印最後一本書的結果 } else { // 沒有輸入!警告讀者 std::cerr << "No data?!" << std::endl; return -1; // 表示失敗 } return 0; }
// 測試數據 0-201-78345-X 4 25.0 0-201-78345-X 1 25.0 0-201-78345-X 2 25.0 0-201-78345-X 9 25.0 0-207-78345-X 9 31.0 0-207-78345-X 3 31.0 0-202-78345-X 3 20.0 0-202-78345-X 3 20.0 // 運行結果 0-201-78345-X 16 400 25 0-207-78345-X 12 372 31