codeup taxi fares (C ++)

Title Description

A city taxi meter rules are as follows: initial four kilometers $ 10, even if you do not trip over 4 km; the next four kilometers and 2 yuan per kilometer; after 2.4 yuan per kilometer. Last leg of even less than 1 km, but also as one kilometer charge.
Passengers can arrange a car to travel a few kilometers According to minimize their fight fare.
For example, the entire stroke of 16 km, the passenger will be the same stroke length is divided into two parts, each spent $ 18, a total cost 1.20. If you take a taxi the whole journey to spend 37.2 yuan.
Now to give you the whole trip a few kilometers, you take a taxi minimum cost of computing.

Entry

Test input comprising a plurality of sets of data. Each enter a positive integer n (n <10000000), km represents the entire trip.
When n = 0, the input end.

Export

Minimum cost for each set of input and output. If necessary, to one decimal place.

Sample input  Copy

3
9
16
0

Sample output Copy

10
20.4
36

Outline of Solution: This problem is a greedy, it must first find the optimal spend the time periods, when 0 <rode <= 4, takes a minimum 10; when 4 <rode <= 8, takes a minimum of 10 + (rode - 4) * 2 million; when rode> 8, a different situation occurs, referred to as 8 km exceeding a kilometer: ① when when 0 <a <= 4, to continue to take a taxi to spend less; ② when 4 <a <= 5, again a taxi, continue car takes about the same (implementation code to this case classified as re taxi in); ③ when 5 <a, the re taxi more cost-effective, and because repeated closest start mentioned case, then so rode - = 8; money + = 18; take are restarted.

Precautions: When beginning to realize, will rode - = 8; money + = 18; This code is also written as a function of demand taxi spent, resulting in excess memory. Later this code into the main function obtained after out.

code show as below:

#include<bits/stdc++.h>
using namespace std;
double fee(int rode){
	if(rode <= 4) return 10;
	else if(rode <= 8) return 10 + (rode - 4) * 2;
	else if(rode <= 12) return 18 + (rode - 8) * 2.4;
	else return 0;
} 
int main(){
	int rode;
	while(scanf("%d",&rode),rode){
		double money = 0;
		while(rode > 12){
			rode -= 8;
			money += 18;
		}
		money += fee(rode);
		if(money - (int)money > 0)  printf("%.1lf\n",money);
		else printf("%d\n",(int)money);
	}
}

 

Published 32 original articles · won praise 2 · Views 1611

Guess you like

Origin blog.csdn.net/qq_38969094/article/details/104388687