我正試圖用C++解決一些編程練習(我是新手)。這個練習需要計算公共汽車(公共交通)的日常利潤,並打印獲得最高利潤的公共汽車的名稱,以及每日利潤和所有公共汽車的利潤總和。然而,根據乘客的票數不同(1,2,3,4,5或6):1滿員滿= 3,2爲教師= 25.5,3爲學生= 22.10和4,5 ,6個是免費的。 這裏是我的代碼:C++計算巴士每日利潤(小錯誤?)
#include <iostream>
#include <string.h>
#include <iomanip>
using namespace std;
int main()
{
int n, j;
double full_ticket=0, teacher_ticket=0, std_ticket=0, foreign_ticket=0, polis_card=0, elderly_card=0; //declare tickets
char ticket, c;
string bus, hBus; //declare strings for bus names
double fuel_amount, fuel_price, daily_profit,busProfit, hAmount, total_amount;
cin>>n>>fuel_price;
for (j=1;j<=n;j++)
{
cin>>bus>>fuel_amount; //read string and amount of fuel consumed
do
{
cin>>ticket>>c; //read ticket type and c is comma, after each ticket there **needs** to be a comma
if(ticket=='1')
{
full_ticket=full_ticket+30;
total_amount=total_amount+full_ticket;
}
if(ticket=='2')
{
teacher_ticket=teacher_ticket+25.5;
total_amount=total_amount+teacher_ticket;
}
if(ticket=='3')
{
std_ticket=std_ticket+22.10;
total_amount=total_amount+std_ticket;
}
if(ticket=='4')
{
foreign_ticket=foreign_ticket+0;
total_amount=total_amount+foreign_ticket;
}
if(ticket=='5')
{
polis_card=polis_card+0;
total_amount=total_amount+polis_card;
}
if(ticket=='6')
{
elderly_card=elderly_card+0;
total_amount=total_amount+elderly_card;
}
}while(c!=';'); //termination of do-while loop when it reads a semicolon
//calculate sum per each bus
busProfit=(full_ticket+teacher_ticket+std_ticket+foreign_ticket+polis_card+elderly_card)-(fuel_amount*fuel_price);
daily_profit=daily_profit+busProfit; //calculate daily profit of buses
if(busProfit>hAmount) //set condition for highest bus
{
hAmount=busProfit;
hBus=bus;
}
full_ticket=0; teacher_ticket=0; std_ticket=0; foreign_ticket=0;polis_card=0;elderly_card=0;
//set variables to 0 before loop starts again
}
cout<<fixed<<setprecision(2);
cout<<hBus<<" "<<hAmount<<endl; //print highest bus and highest amount
cout<<daily_profit; //print daily profit
return 0;
}
此代碼似傳所有基本的測試,因爲它沒有被接受,但是有一些毛病。如果你能幫我找到錯誤,我將不勝感激。
如果您可以在您的代碼上使用調試器,我們將不勝感激。每次執行一個語句並觀察變量值。請編輯您的帖子,指出哪個語句導致問題以及原因。 –
@ThomasMatthews是正確的,調試器會指出導致問題的代碼的某一行。運行調試器併發布導致問題的行。 –
'switch'語句可能比多個'if'語句更具可讀性。 –