在第二章的末尾,我被塞进了一个练习中!这个练习的问题是,我不知道如何使逻辑循环要求输入数倍!我写了代码,要求输入两次!以前,有了书的标题,我很容易就完成了这个任务,但是那样的方法已经行不通了。所以我会给你练习和代码,希望你能帮我。为我的英语道歉。
运动
编写程序,它将有一个类在相同的地方,您的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;
} 同时也肯定了原因,但营收给了我垃圾号。谢谢您抽时间见我。
发布于 2013-04-24 02:13:00
你是在使用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;
}https://stackoverflow.com/questions/16182237
复制相似问题