首页 > 解决方案 > 如何检查用户输入的字符串是否代表浮点值?

问题描述

我正在从事这个项目,您可以在其中喂养和锻炼您的宠物以使它们保持活力。在喂食方面,游戏会询问您想要喂宠物多少零食。为了获得及格分数,我需要代码来检测用户的输入是否为浮点数。因此,当输入字符串而不是浮点数时,我需要它说“请输入一个数字”。有任何想法吗?

    // Function for feeding pet
static void FeedPet(ref float PetWeight, List<string> FeedList, List<string> ExoList, ref string PetName)
{
    bool repeat = true;
    while (repeat)
    {
        Math.Round(PetWeight, 2);
        Console.WriteLine("|=-=-=-=-=| FEED |=-=-=-=-=|");
        Console.Write($"Please enter the amount of treats you would like to feed {PetName}: ");
        float FoodAmount = float.Parse(Console.ReadLine());
        float GainedWeight = (float)(FoodAmount * 0.02f);

        if ( FoodAmount == 0)
        {
            Console.WriteLine($"No treats for {PetName} today");
            Console.WriteLine($"{PetName} currently weighs {PetWeight}");
            repeat = false;
        }
        if ((FoodAmount >= 1) && (FoodAmount <= 5)) 
        {
            // Formula for new pet weight
            PetWeight = FoodAmount * 0.2f + PetWeight;
            // Telling user how much weight the pet gained
            Console.WriteLine($"{PetName} gained {GainedWeight}kgs");
            // Adding info to list
            FeedList.Add($"{PetName} ate {FoodAmount} treats and gained {GainedWeight}kgs ");
            // Display current weight message to user
            Console.WriteLine($"Current weight is now: {PetWeight}kgs");
            repeat = false;
        }
        else
        {
            Console.WriteLine($"{PetName} can only eat up to 5 treats at a time. Please enter a number that ranges from 0 - 5");
        }
    }

}

标签: c#

解决方案


推荐阅读