需要帮助修复错误的输出到控制台窗口。

时间:2018-04-08 22:39:08

标签: c#

我正在为学校分配工作,该工作包括Program.cs文件和一个名为Car的单独类。我已经编写了Car类的所有代码,并将已经提供的代码粘贴到program.cs文件中。结果输出是

2010 Ford Focus is going 20 MPH.
2018 Chevy Cruze is going 0 MPH.

该作业要求预期的

输出
2010 Ford Focus is going 28 MPH.
2018 Chevy Cruze is going 18 MPH.

我需要知道如何让窗口输出汽车1的预期速度28和汽车2的18。我假设我不应该改变提供的代码program.cs来完成应用程序/赋值的正确输出。

public class Car
{
    private int Speed;
    private string Make;
    private string Model;
    private int Year;

    public Car (string make, string model, int year, int speed)
    {
        this.Make = make;
        this.Model = model;
        this.Year = year;
        this.Speed = speed;
    }

    public Car(string make, string model, int year)
    {
        this.Make = make;
        this.Model = model;
        this.Year = year;
        this.Speed = 0;
    }

    public int SpeedUp()
    {
        this.Speed = Speed++;
        return (Speed);
    }

    public int SlowDown()
    {
        if (Speed > 0)
        {
            this.Speed = Speed--;   
        }

        return (Speed);
    }

    public void Display()
    {
        Console.WriteLine(Year + " " + Make + " " + Model + " is going " + Speed + " MPH.");
        Convert.ToString(Console.ReadLine());
    }
}

以下是program.cs中的给定代码

class Program
{
    static void Main(string[] args)
    {
        int car1Speed = 20;
        int car2Speed = 0;
        Car car1 = new Car("Ford", "Focus", 2010, car1Speed);
        Car car2 = new Car("Chevy", "Cruze", 2018, car2Speed);

        for (int i = 0; i < 60; i++)
        {
            if (i % 2 == 0)
            {
               car2Speed = car2.SpeedUp();
            }
            if (i % 3 == 0)
            {
                car1Speed = car1.SpeedUp();
            }
            if (i % 5 == 0)
            {
                car1Speed = car1.SlowDown();
                car2Speed = car2.SlowDown();
            }
        }

        car1.Display();
        car2.Display();
    }
}

2 个答案:

答案 0 :(得分:2)

在Car.cs类中,这是一种在不修改Program.cs文件的情况下提高速度的更好方法:

public int SpeedUp()
{
    this.Speed += 1;
    return (Speed);
}
public int SlowDown()
{
    if (Speed > 0)
    {
        this.Speed -= 1;
    }
    return (Speed);
}

这会产生您之后的输出。

答案 1 :(得分:2)

代码行

this.Speed = Speed++;

对this.Speed的值没有影响。

代码行大致相当于

int temp = this.Speed; // We store the original value of Speed.
this.Speed = Speed + 1; // We add one to Speed and assign it back to Speed.
this.Speed = temp; // We immediately replace Speed with the original value of Speed.

这是由于'++'运算符的行为,当附加到变量的末尾时,它会将1添加到其当前值,然后将结果赋给变量。但是,此运算符会临时存储原始值,并将其用作表达式的结果。这个++运算符的临时结果最终是由于你在同一个表达式中使用的'='运算符而赋予this.Speed的结果,这反过来又导致变量实际上没有被修改。< / p>

正确的用法是简单地调用

Speed++;

这将执行添加1和分配回Speed,并且还丢弃临时变量,因为它没有被分配到任何地方。

使用' - '运算符在SpeedDown方法中也存在此问题。