0

我被困在第 2 章末尾的 1 个练习中!我对这个练习的问题是我无法弄清楚如何在逻辑上循环询问多次输入!我编写了两次要求输入的代码!以前用书提供的标题我很容易完成这项任务,但这种方式不再起作用了。所以我会给你练习和代码,希望你能帮助我。对不起我的英语。

练习
编写程序,该程序将在您工作的地方有一个类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;          
}   

而且也不确定为什么,但收入给了我垃圾号码。感谢您的时间。

4

1 回答 1

0

data2.revenue在使用它之前初始化了吗?

data2.revenue=data2.revenue*price;

要 init 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;
}
于 2013-04-24T02:13:00.350 回答