我正在尝试用C ++解决一些编程练习(我是新手)。该练习需要计算公共汽车(公共交通)的每日利润,并打印出利润最高的公交车名称,以及每日利润和所有公交车的总利润之和。然而,根据乘客的不同,门票有不同的类型(1,2,3,4,5或6):1是满,满= 3,2为教师= 25.5,3为学生= 22.10和4,5 ,6是免费的。 这是我的代码:
#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;
}
这段代码似乎通过了所有初级测试,但由于它尚未被接受,因此它有问题。如果你能帮我找到错误,我将不胜感激。
答案 0 :(得分:2)
两个问题,虽然第二个问题可能不相关,因为我认为除了计算之外没有使用total_amount
:
daily_profit
在使用之前从未初始化。
total_amount
的值对于以下内容不正确:
if(ticket=='1')
{
full_ticket=full_ticket+30;
total_amount=total_amount+full_ticket;
}
在上面的代码中,您要将full_ticket
的费用添加到我假设的是您通过销售完整门票所赚取的总金额。然后,将该值添加到total_amount
。问题是,你真的只想添加30到total_amount
,因为你计算每次添加的每张票的价值,而不是一张票的价值。
第一张票:full_ticket = 30, total_amount = 30
第二张票:full_ticket = 60, total_amount = 90
第三张票:full_ticket = 90, total_amount = 180
这种模式会重复其他票价。