码迷,mamicode.com
首页 > 编程语言 > 详细

《c++ primer》书店程序——Chapter2

时间:2020-01-09 01:28:57      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:actions   end   span   number   ota   primer   cti   second   eth   

Sales_data.h

 1 #ifndef SALES_DATA_H
 2 #define SALES_DATA_H
 3 
 4 #include "Version_test.h"
 5 
 6 #include <string>
 7 
 8 struct Sales_data {
 9     std::string bookNo;
10 #ifdef IN_CLASS_INITS
11     unsigned units_sold = 0;
12     double revenue = 0.0;
13 #else
14     unsigned units_sold;  
15     double revenue;
16 #endif
17 };
18 #endif
  • 定义了Slaes_data类
  • 作者想让读者自己定义一遍Sales_item类,所以在此没有定义操作

Sales_data.cpp

 1 #include <iostream>
 2 #include <string>
 3 #include "Sales_data.h"
 4 
 5 int main()
 6 {
 7     Sales_data data1, data2;
 8 
 9     // code to read into data1 and data2
10     double price = 0;  // price per book, used to calculate total revenue
11 
12     // read the first transactions: ISBN, number of books sold, price per book
13     std::cin >> data1.bookNo >> data1.units_sold >> price;
14     // calculate total revenue from price and units_sold
15     data1.revenue = data1.units_sold * price;
16 
17     // read the second transaction
18     std::cin >> data2.bookNo >> data2.units_sold >> price;
19     data2.revenue = data2.units_sold * price;
20 
21     // code to check whether data1 and data2 have the same ISBN
22     //        and if so print the sum of data1 and data2
23     if (data1.bookNo == data2.bookNo) {
24         unsigned totalCnt = data1.units_sold + data2.units_sold;
25         double totalRevenue = data1.revenue + data2.revenue;
26 
27         // print: ISBN, total sold, total revenue, average price per book
28         std::cout << data1.bookNo << " " << totalCnt 
29                   << " " << totalRevenue << " ";
30         if (totalCnt != 0)
31             std::cout << totalRevenue/totalCnt << std::endl;
32         else
33             std::cout  << "(no sales)" << std::endl;
34 
35         return 0;  // indicate success
36     } else {  // transactions weren‘t for the same ISBN
37         std::cerr << "Data must refer to the same ISBN" 
38                   << std::endl;
39         return -1; // indicate failure
40     }
41 }
  • 读入data1和data2的代码
  • 检查data1和data2的ISBN是否相同
  • 如相同,求data1和data2的和

《c++ primer》书店程序——Chapter2

标签:actions   end   span   number   ota   primer   cti   second   eth   

原文地址:https://www.cnblogs.com/cxc1357/p/12169219.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!