• [笔记] 《c++ primer》书店程序 Chapter2


    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的和
  • 相关阅读:
    八、JVM视角浅理解并发和锁
    七、JVM类加载机制
    六、JVM命令和工具
    五、jvm垃圾回收3(几种垃圾收集器)
    四、JVM垃圾回收2(垃圾收集算法)
    jvm引用类型
    三、JVM垃圾回收1(如何寻找垃圾?)
    【原创】Android 对话框的使用
    【原创】CMD常用命令:解决实际问题
    【原创】开机出现grub rescue,修复办法
  • 原文地址:https://www.cnblogs.com/cxc1357/p/12169219.html
Copyright © 2020-2023  润新知