Description
Problem A: Average Speed
You have bought a car in order to drive from Waterloo to a big city. The odometer on their car is broken, so you cannot measure distance. But the speedometer and cruise control both work, so the car can maintain a constant speed which can be adjusted from time to time in response to speed limits, traffic jams, and border queues. You have a stopwatch and note the elapsed time every time the speed changes. From time to time you wonder, "how far have I come?". To solve this problem you must write a program to run on your laptop computer in the passenger seat.
Standard input contains several lines of input: Each speed change is indicated by a line specifying the elapsed time since the beginning of the trip (hh:mm:ss), followed by the new speed in km/h. Each query is indicated by a line containing the elapsed time. At the outset of the trip the car is stationary. Elapsed times are given in non-decreasing order and there is at most one speed change at any given time.
For each query in standard input, you should print a line giving the time and the distance travelled, in the format below.
Input
Output
Sample Input
00:00:01 100
00:15:01
00:30:01
01:00:01 50
03:00:01
03:00:05 140
Sample Output
00:15:01 25.00 km
00:30:01 50.00 km
03:00:01 200.00 km
题意:输入若干行,如果只有时间没有速度,要求输出现在的时间和所走的总路程,如果有速度,表示在该时间改变了速度。
解析:因为不知道输入格式是哪一种,因此我们得用getline读入一行然后判断,然后保存上次的时间Last,当前时间为t,时间差为t-last,速度为v,计算出路程然后加上,注意单位。
#include <iostream>
#include <string>
#include <cstdio>
using namespace std;
int main()
{
string a;
double S=0,v=0;//路程和速度
int last=0,h,f,s,t;
while(getline(cin,a))
{
h=(a[0]-'0')*10+a[1]-'0';
f=(a[3]-'0')*10+a[4]-'0';
s=(a[6]-'0')*10+a[7]-'0';
t=h*3600+f*60+s;//当前时间
S+=(t*1.0-last)*v/1000;//时间差为t-last,速度为v
last=t;//更新last
if(a.size()>8)//给出时间和速度
{
v=0;
for(int i=9;i<a.size();i++) v=v*10+a[i]-'0';
v/=3.6;//米/秒
}else printf("%02d:%02d:%02d %.2lf km\n",h,f,s,S);
}
return 0;
}