0

コンストラクターが呼び出しているメソッドにデータを入れることができ、それが機能することを認識しています。ただし、コードをいじっているだけで、追加のメソッドに計算を実行させようとしています。これは本の問題であり、バグを報告するインストラクターが数週間いないため、ここで質問することにしました。

入力はありますか?よろしくお願いします

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

 namespace ConsoleApplication305
{
class Program
{
    static void Main(string[] args)
    {
        Trip a = new Trip();
        Console.WriteLine(a);

    }

    class Trip
    {
        int distanceTraveled;
        double costGas;
        int numberGallon;
        int mpg;
        double cpm;

        public int DistanceTraveled
        {
            get
            {
                return distanceTraveled;
            }
        }
        public double CostGas
        {
            get
            {
                return costGas;
            }
        }
        public int NumberGallon
        {
            get
            {
                return numberGallon;
            }
        }

        public Trip()
        {
            distanceTraveled = 312;
            costGas = 3.46;
            numberGallon = 10;

        }

        public void milesPerGal()
        {
            mpg = distanceTraveled / numberGallon;
        }

        public void costPerMile()
        {
            cpm = costGas * mpg;
        }

        public override string ToString()
        {
            return String.Format("The distance traveled is...{0} \nThe cost per gallon of gasoline is... {1} \nThe amount of gallons were... {2} \nThe miles per gallon attained were... {3} \nThe cost per MPG were... {4}", distanceTraveled, costGas, numberGallon, mpg, cpm);
        }
    }
}

}

4

2 に答える 2

1

正直に言うと、ここではすべてがうまく機能します。メソッド milesPerGal または costPerMile を呼び出したことがないため、プライベート変数 mpg および cpm の値はまだ 0 であり、これも同様に出力されます。

おそらくあなたが望んでいたのは、このコンストラクターでした:

public Trip()
{
    distanceTraveled = 312;
    costGas = 3.46;
    numberGallon = 10;
    milesPerGal();
    costPerMile();
}

このコードを期待どおりに機能させるには、次のような適切なゲッターとセッターを使用することをお勧めします。

class Trip
{
    public int DistanceTraveled { get; set; }
    public double CostGas { get; set; }
    public int NumberGallon { get; set; }
    public int MilesPerGallon { get { return (NumberGallon != 0) ? DistanceTraveled / NumberGallon : 0; } }
    public double CostPerMile { get { return CostGas * MilesPerGallon; } }

    public Trip()
    {
        DistanceTraveled = 312;
        CostGas = 3.46;
        NumberGallon = 10;
    }

    public override string ToString()
    {
        return String.Format("The distance traveled is...{0} \nThe cost per gallon of gasoline is... {1} \nThe amount of gallons were... {2} \nThe miles per gallon attained were... {3} \nThe cost per MPG were... {4}", DistanceTraveled, CostGas, NumberGallon, MilesPerGallon, CostPerMile);
    }
}

このアプローチでは、セッター ( DistanceTraveledCostGasおよびNumberGallons) を持つフィールドのいずれかを更新するたびに、それぞれの派生値 (MilesPerGallonおよびCostPerMile) が追加のメソッド呼び出しなしで自動的に修正されることに注意してください。これらのフィールドにアクセスします。

于 2013-08-16T00:43:14.963 に答える