好的,所以分配是从名为tickets.txt的文件中获取输入,并输出售出的门票总数以及总收入。文本文件中的值输入两列(1)售出的票数,以及(2)每种票类的价格。
文本文件如下:
250 5750
100 28000
50 35750
25 18750
这是我想出的代码......
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
/* Program Name: Ticket_Sales.cpp
* Date: May 2, 2018
* Purpose: Calculate Total Ticket Sales
*/
int main() {
{
ifstream inFile;
float ticket_cost;
float tickets_sold;
float total_cost ;
float total_sold ;
float ticket_revenue;
/*
* I noticed someone doing something similar to this on StackExchange; seems absolutely brilliant to include
* a manner to check if the program is accessing the file.
*/
inFile.open("C:\\Users\\pinkp\\CLionProjects\\M05_Ticket_Sales\\tickets.txt");
if (inFile.fail()) {
cout << "Failed to open the file." << endl;
cin.get ();
return 1;
}
while(inFile >> tickets_sold >> ticket_cost) {
total_sold += tickets_sold;
total_cost += ticket_cost;
ticket_revenue = (total_cost * total_sold);
}
cout << fixed << setprecision(2);
cout << "Total Tickets Sold: " << total_sold << "." << endl;
cout << "Total Revenue: " << ticket_revenue << "." << endl;
}
/*
* The value continues to return 2 less than the intended output, and I cannot pinpoint the exact cause.
*/
return 0;
}
但是我对ticket_revenue的输出继续给我37506248.00,当手动将数字输入计算器时会给你37506250.00。两个数字的差异。我想过要做一个&#39; + 2&#39;把它弄到正确的数字,但我认为我的教授会对此不以为然。
无论ticket.txt中的数字是什么(我已经改变了几次),它总是比我期望的少两个。这是一些超级简单的C ++或编程概念吗?我曾经错过了什么?
谢谢!
答案 0 :(得分:6)
您无法初始化ticket_revenue
- 并查看其分配方式:
ticket_revenue = (total_cost * total_sold);
这会使用总出售的门票数量和所有价格的总和的产品覆盖ticket_revenue
。
你需要像(未经测试的):
unsigned long total_sold = 0;
unsigned long ticket_revenue = 0;
while (inFile >> tickets_sold >> ticket_cost) {
auto transaction_revenue = tickets_sold * ticket_cost;
total_sold += tickets_sold;
ticket_revenue += transaction_revenue;
}
BTW,don't use floating-point types for currency calculations!
这是代码的一个版本,修复了上述错误,没有外部输入文件(因此它代表Minmal, Complete and Verifiable Example):
#include <iostream>
#include <vector>
int main()
{
static const
std::vector<std::pair<int, long>> sales =
{{ 250, 5750 },
{ 100, 28000 },
{ 50, 35750 },
{ 25, 18750 } };
long total_sold = 0;
long ticket_revenue = 0;
for (auto& sale: sales) {
int tickets_sold = sale.first;
long ticket_cost = sale.second;
total_sold += tickets_sold;
ticket_revenue += tickets_sold * ticket_cost;
}
std::cout << "Total Tickets Sold: " << total_sold << ".\n";
std::cout << "Total Revenue: " << ticket_revenue << ".\n";
}
这会产生正确的答案:
Total Tickets Sold: 425.
Total Revenue: 6493750.
答案 1 :(得分:2)
我认为相反
while(inFile >> tickets_sold >> ticket_cost) {
total_sold += tickets_sold;
total_cost += ticket_cost;
ticket_revenue = (total_cost * total_sold);
}
你应该写
ticket_revenue = 0;
while(inFile >> tickets_sold >> ticket_cost) {
ticket_revenue += ticket_sold * ticket_cost;
}
否则,您总结门票数量和门票费用,您应该获得更大的价值。