Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

antonfotev avatar antonfotev 4 Точки

More Exercises: Objects and Classes - 3. Speed Racing

Здравейте колеги. Дава ми 40 точки на следната задача.
Условието е следното:
3. Speed Racing
Your task is to implement a program that keeps track of cars and their fuel and supports methods for moving the
cars. Define a class Car that keeps a track of a car’s model, fuel amount, fuel consumption for 1 kilometer and
traveled distance. A Car’s model is unique - there will never be 2 cars with the same model.
On the first line of the input you will receive a number N – the number of cars you need to track, on each of the
next N lines you will receive information about a car in the following format “<Model> <FuelAmount>
<FuelConsumptionFor1km>”. All cars start at 0 kilometers traveled.
After the N lines, until the command "End" is received, you will receive commands in the following format "Drive
<CarModel> <amountOfKm>". Implement a method in the Car class to calculate whether or not a car can move
that distance. If it can, the car’s fuel amount should be reduced by the amount of used fuel and its traveled
distance should be increased by the number of the traveled kilometers. Otherwise, the car should not move (its fuel
amount and the traveled distance should stay the same) and you should print on the console “Insufficient fuel for
the drive”. After the "End" command is received, print each car and its current fuel amount and the traveled
distance in the format "<Model> <fuelAmount> <distanceTraveled>". Print the fuel amount rounded to
two digits after the decimal separator.

Кодът ми е следния:

using System;
using System.Collections.Generic;
using System.Linq;

public class Car
{
 public double FuelAmount {get; set;}
    
 public double FuelConsumptionFor1km {get; set;}
    
 public int TraveledKilometers {get; set;}     
    
 public void TryTraveledThisDistance(int currentDistanse)
 {
    double amountOfFuelRequired =  FuelConsumptionFor1km * currentDistanse;
     if(FuelAmount > amountOfFuelRequired)
     {
        FuelAmount -= amountOfFuelRequired; 
        TraveledKilometers += currentDistanse;
     }
     else
     {
        Console.WriteLine("Insufficient fuel for the drive"); 
     }
 }     
} // end class Car
                    
public class Program
{
    public static void Main()
    {
        var orderCar = new Dictionary<string, Car>();
        
        int n = int.Parse(Console.ReadLine());
        for(int i = 0; i < n; i++)
        {
          string[] input = Console.ReadLine()
              .Split();
            
            string model = input[0];
            double fuelAmount = double.Parse(input[1]);
            double fuelConsumptionFor1km = double.Parse(input[2]);
            
            orderCar[model] = new Car{FuelAmount = fuelAmount, FuelConsumptionFor1km = fuelConsumptionFor1km};
        } // end for
        
        string inputPrim = null;
        while ((inputPrim = Console.ReadLine()) != "End")
        {
         string[] input = inputPrim
              .Split();    
            
            string currentModel = input[1];
            int currentDistanse = int.Parse(input[2]);
            
            foreach (var kvp in orderCar)
            {
                if (kvp.Key == currentModel)
                {
                 kvp.Value.TryTraveledThisDistance(currentDistanse);    
                }
            } // end foreach for TryTraveledThisDistance
        } // end while for Drive
        
        foreach (var kvp in orderCar)
        {
            // AudiA4 1.00 50
            Console.WriteLine("{0} {1:0.00} {2}", kvp.Key,kvp.Value.FuelAmount, kvp.Value.TraveledKilometers);
        }
    }
}

// 2
// AudiA4 23 0.3
// BMW-M2 45 0.42
// Drive BMW-M2 56
// Drive AudiA4 5
// Drive AudiA4 13
// End
// 
// AudiA4 17.60 18
// BMW-M2 21.48 56

// 3
// AudiA4 18 0.34
// BMW-M2 33 0.41
// Ferrari-488Spider 50 0.47
// Drive Ferrari-488Spider 97
// Drive Ferrari-488Spider 35
// Drive AudiA4 85
// Drive AudiA4 50
// End
// 
// Insufficient fuel for the drive
// Insufficient fuel for the drive
// AudiA4 1.00 50
// BMW-M2 33.00 0
// Ferrari-488Spider 4.41 97

 

Тагове:
0
Teamwork and Personal Skills
HudsonJoseland avatar HudsonJoseland 0 Точки

This Beautiful message is displayed by the network and board individuals from Parkside Middle School. This school is continually being an agent for understudies as they generally control understudies towards their point. As this article is about the arithmetic so I should welcome it since science is the main subject which open our mind and expand our reasoning force.and here you can check it is essayshark legit for best and unique work. All the key variables depicted in this article found very genuine and enlightening. So I truly like the article and expectation that others will like it as well.

-1
kathleenswafford avatar kathleenswafford -3 Точки

I have just visited your website, and I am glad to read the article's blade runner 2049 coat. The quality of the blogs is amazing, very well written and the language is extremely easy.

-1
kathleenswafford avatar kathleenswafford -3 Точки

This is my first visit to your site. You are providing a good articles. Now I am feeling a lot because for a longtime, I have missed your site. Concept is too good. Money heist costume

-1
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.