【问题标题】:C# Decimal user input with response带有响应的 C# 十进制用户输入
【发布时间】:2016-03-09 17:36:12
【问题描述】:

首先我想说我对 C# 还很陌生,我对它的了解并不是很好,但是我查看了不同的站点并没有找到解决方案(或者也许我找到了但我失败了) 无论如何,我正在尝试实现一个功能,让用户输入他的 GPA 分数(例如 4.5),如果它包含字母或其他字符(例如 4.5a$g),它会返回要求输入数字。 这是我目前拥有的:

Console.WriteLine("\nGPA Score: ");
userinput2 = Console.ReadLine();
int Result = 0;
bool TGPA = int.TryParse(userinput2, out Result);

if (TGPA)
{
     Console.WriteLine(Result);
}
else
{
     Console.WriteLine("Please enter a numerical value.");
}

【问题讨论】:

  • 我会更深入地研究该语言,它们中的大多数都有正则表达式(使用正则表达式来确保在你的情况下只允许数字和小数)。

标签: c# output decimal


【解决方案1】:

请写一个循环,直到你得到一个有效的数字(在这种情况下是小数)。

        Console.WriteLine("\nGPA Score: ");
        string userinput2 = Console.ReadLine();
        decimal Result = 0;

        bool TGPA = decimal.TryParse(userinput2, out Result);

        while (TGPA == false)
        {
            Console.WriteLine("{0} is not a valid number, please try again", userinput2);
            userinput2 = Console.ReadLine();
            Result = 0;
            TGPA = decimal.TryParse(userinput2, out Result);
        }

【讨论】:

    【解决方案2】:

    (例如 4.5)

    这不是整数。试试小数:

    decimal Result = 0M;
    bool TGPA = decimal.TryParse(userinput2, out Result);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多