C ++ Primer练习2.41

时间:2013-04-24 02:10:22

标签: c++

我坚持参加第2章结尾的一次练习!我的这个练习的问题是我无法弄清楚如何进行逻辑循环来多次询问输入!我写了两次输入的代码!以前使用书籍提供的标题我很容易完成这项任务,但这种方式不再适用。所以我会给你练习和代码,希望你能帮助我。对不起我的英语。

运动
编写程序,该程序将在main运行的同一位置具有一个类 编写代码,该代码将读取具有相同书号的多个交易,并使用该书号对每个交易进行计数。

我的代码

#include <iostream>
#include <string>
using namespace std;

//Data structure Code 
struct Sales_Data
{
std::string bookNo;
unsigned unit_sold;
double revenue;
};
int main()
{

Sales_Data data1,data2; //Data wich will hold input 
double price;           //Price per book used to calculate total revenue

// Checking if there was data input of book number units sold and price
if (std::cin>>data1.bookNo>>data1.unit_sold>>price)
{
    int cnt=1;  //Start Counter 
    data1.revenue=data1.unit_sold*price;// data1 calculating total revenue from price and unit_sold 

    while (std::cin>>data2.bookNo>>data2.unit_sold>>price)
    {
        data2.revenue=data2.revenue*price;

              //checking if book name is same
        if (data1.bookNo == data2.bookNo)
        {
            ++cnt; //Incrementing counter if they same
            unsigned totalCnt=data1.unit_sold+data2.unit_sold;
            double totalRevenue=data1.revenue+data2.revenue;
            //Print out result
            std::cout<<cnt<<data1.bookNo<<" "<<totalCnt<<" "<<totalRevenue<<" ";
            getchar();
            getchar();
            getchar();
            if (totalCnt != 0)

                std::cout<<totalCnt/totalRevenue;
            else 
                std::cout<<"(No Sales)"<<std::endl;
                return 0;
        }else{
            std::cerr<<"Book numbers isn't same"<<std::endl;
            return -1;
        }           
    }
}
return 0;          
}   

并且还确定为什么,但收入给了我垃圾号码。 谢谢你的时间。

1 个答案:

答案 0 :(得分:0)

在使用之前是否已初始化data2.revenue

data2.revenue=data2.revenue*price;

要初始化data2,您可以:

struct Sales_Data
{
    std::string bookNo;
    unsigned unit_sold;
    double revenue;

    Sales_Data(std::string s = "", unsigned u = 0, double r = 0)
        : bookNo(s), unit_sold(u), revenue(r) {}
};

Sales_Data data2 = { "a", 0, 0 };

Sales_Data data2;
data2.bookNo = "";
data2.unit_sold = 0;
data2.revenue = 0;

对于多个输入:

#include <map>
#include <string>
#include <iostream>
using namespace std

int main()
{
    map<string, Sales_Data> count;
    Sales_Data data;

    while (cin >> data.bookNo >> data.unit_sold) { // <- this will allow you read multiple transactions

        if (map.find(data.bookNo) != count.end()) {
            count[data.bookNo].unit_sold += data.unit_sold;
            // and do some other thing.
        } else {
            count[data.bookNo] = data.
        }
    }
    return 0;
}