計算機科学のブログ

data, types, objects, and references - Managing your app's data - Fix the compiler error by adding a cast

Head First C Sharp: A Learner’s Guide to Real-World Programming with C Sharp and .NET (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)の Chapter 4(data, types, objects, and references - Managing your app’s data)、p.213(Exercise)の解答を求めてみる。

コード

Program.cs

using System.ComponentModel;
using AbilityScore;

AbilityScoreCalculator calculator = new AbilityScoreCalculator();
while (true)
{
    calculator.Rollresult = ReadInt(calculator.Rollresult, "Starting 4d6 roll");
    calculator.DivideBy = ReadDouble(calculator.DivideBy, "divide by");
    calculator.AddAmount = ReadInt(calculator.AddAmount, "Add amount");
    calculator.Minimum = ReadInt(calculator.Minimum, "Minimum");
    calculator.CalculateAbilityScore();
    Console.WriteLine($"Calculated ability score: {calculator.Score}");
    Console.WriteLine("Press Q to quit, any other key to continue");
    char keyChar = Console.ReadKey(true).KeyChar;
    if ((keyChar == 'Q') || (keyChar == 'q'))
    {
        return;
    }
}

static int ReadInt(int defaultValue, string prompt)
{
    Console.Write($"{prompt} [{defaultValue}] ");
    if (int.TryParse(Console.ReadLine(), out int result))
    {
        return result;
    }
    return defaultValue;
}
static double ReadDouble(double defaultValue, string prompt)
{
    Console.Write($"{prompt} [{defaultValue}] ");
    if (double.TryParse(Console.ReadLine(), out double result))
    {
        return result;
    }
    return defaultValue;
}

コード

AbilityScoreCalculator.cs

namespace AbilityScore;

public class AbilityScoreCalculator
{
    public int Rollresult = 14;
    public double DivideBy = 1.75;
    public int AddAmount = 2;
    public int Minimum = 3;
    public int Score;

    public void CalculateAbilityScore()
    {
        double divided = Rollresult / DivideBy;
        int added = AddAmount += (int)divided;
        if (added < Minimum)
        {
            Score = Minimum;
        }
        else
        {
            Score = added;
        }
    }
}

入出力結果(Terminal, Zsh)

% dotnet run
Starting 4d6 roll [14] 
divide by [1.75] 
Add amount [2] 
Minimum [3] 
Calculated ability score: 10
Press Q to quit, any other key to continue
Starting 4d6 roll [14] 10
divide by [1.75] 
Add amount [10] 
Minimum [3] 
Calculated ability score: 15
Press Q to quit, any other key to continue
Starting 4d6 roll [10] 20
divide by [1.75] 
Add amount [15] 
Minimum [3] 
Calculated ability score: 26
Press Q to quit, any other key to continue
Starting 4d6 roll [20] 
divide by [1.75] 1
Add amount [26] 
Minimum [3] 
Calculated ability score: 46
Press Q to quit, any other key to continue
Starting 4d6 roll [20] a
divide by [1] a
Add amount [46] 
Minimum [3] 
Calculated ability score: 66
Press Q to quit, any other key to continue
%