• [笔记] 《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的和
  • 相关阅读:
    MarkDown 语言简单使用
    开机自启宽带连网设置问题
    JqueryEasyUI EasyLoader
    JqueryEasyUI $.Parser
    FileUpload一键自动上传
    Git读档
    JavaScript typeof运算符和数据类型
    JavaScript 函数 (function)
    Javascript 对象(Object)
    JavaScript 数组(Array)
  • 原文地址:https://www.cnblogs.com/cxc1357/p/12169219.html
Copyright © 2020-2023  润新知