我是C++的初學者,創建了一個包含計算出的通話費率的輸入文件。我能夠分別計算每次通話的成本;然而,我不知道如何...如何添加循環輸入文件的結果?
把每個電話的結果,並總計在一起。
準確計算從白天到夜間/週日到週末的通話費用。
這是我到目前爲止。任何幫助深表感謝。謝謝!
Call_History.txt
(Day/Time/Duration/Cost)
Mo 1330 16 $6.40
Mo 815 35 $14.00
Tu 750 20 $3.00
We 1745 30 $12.00
Th 800 45 $18.00
Su 2350 30 $4.50
代碼
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
const double DAYTIME = 0.40;
const double NIGHT = 0.25;
const double WEEKEND = 0.15;
int main()
{
ifstream fin;
fin.open("Call_History.txt");
string day;
int time;
int duration;
int dayOfWeek;
double cost;
double total;
// Set the numeric output formatting.
cout << fixed << showpoint << setprecision(2);
cout << "Day Time Duration Cost\n" << endl;
while (fin >> day >> time >> duration)
{
if (day == "Mo")
{
dayOfWeek = 1;
}
else if (day == "Tu")
{
dayOfWeek = 2;
}
else if (day == "We")
{
dayOfWeek = 3;
}
else if (day == "Th")
{
dayOfWeek = 4;
}
else if (day == "Fr")
{
dayOfWeek = 5;
}
else if (day == "Sa")
{
dayOfWeek = 6;
}
else if (day == "Su")
{
dayOfWeek = 7;
}
// Determine cost of call based on rate schedule.
if ((time >= 800) && (time <= 1800) && (dayOfWeek <= 5))
{
cost = duration * DAYTIME;
}
else if ((time < 800) && (time > 1800) && (dayOfWeek <= 5))
{
cost = duration * NIGHT;
}
else
{
cost = duration * WEEKEND;
}
cout << day << " " << time << " " << duration << " $" << cost << endl;
}
cout << "\nTotal $" << endl;
return 0;
}
題外話:你有每行四個輸入或五個標記('莫1330 $ 16 6.40')和三個標記讀取('鰭>>天> >時間>>持續時間)。閱讀價格可能會讓你覺得合適,所以我會在進一步深入之前弄清楚,並且不得不做大量的重新編寫以適應它。 – user4581301
也是關鍵主題:你可以將dayOfWeek變量改爲isWeekday變量,從而將你的if語句從7減少到2.即如果day ==「Mo」| 「屠」 ... – user3605508