【问题标题】:Need help with accepting decimals as input in C#在 C# 中接受小数作为输入时需要帮助
【发布时间】:2011-09-02 16:26:03
【问题描述】:

我用 C# 编写了一个运行勾股定理的程序。我希望在允许程序从用户输入中接受小数点方面得到一些帮助。这就是我所拥有的。

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

    namespace Project_2
{
class Program
{
    static void Main(string[] args)
    {
        int sideA = 0;
        int sideB = 0;
        double sideC = 0;
        Console.Write("Enter a integer for Side A ");
        sideA = Convert.ToInt16(Console.ReadLine());
        Console.Write("Enter a integer for Side B ");
        sideB = Convert.ToInt16(Console.ReadLine());
        sideC = Math.Pow((sideA * sideA + sideB * sideB), .5);
        Console.Write("Side C has this length...");
        Console.WriteLine(sideC);
        Console.ReadLine();

    }
}
} 

我一直在尝试通过使用 Math.Abs​​ 等来研究这个问题,但只是为了接收构建错误。非常感谢您对写入路径的帮助。

【问题讨论】:

  • 在用户输入上使用 Decimal.Parse()
  • 如果我使用它,那么 Math.Pow 函数将停止工作,因为它无法将双精度数转换为小数。

标签: c# visual-studio console-application


【解决方案1】:

我会推荐使用 Decimal.TryParse。这种模式非常安全,因为它会捕获异常并返回一个布尔值来确定解析操作是否成功。

http://msdn.microsoft.com/en-us/library/system.decimal.tryparse.aspx

【讨论】:

  • 吹毛求疵:一般来说,各种TryParse 模式不会“捕获”异常;他们完全避开它们。
  • 很公平,但它们不会向用户公开任何异常。这就是为什么这是一个很好的模式。我也在自定义代码中使用这种模式。
【解决方案2】:

Math.Pow 不采用十进制。关于 Math.Pow 和小数的 SO 已经存在另一个问题。使用双倍。

static void Main(string[] args)
        {
            double sideA = 0;
            double sideB = 0; 
            double sideC = 0; 
            Console.Write("Enter an integer for Side A ");
            sideA = Convert.ToDouble(Console.ReadLine()); 
            Console.Write("Enter an integer for Side B ");
            sideB = Convert.ToDouble(Console.ReadLine()); 
            sideC = Math.Pow((sideA * sideA + sideB * sideB), .5); 
            Console.Write("Side C has this length..."); 
            Console.WriteLine(sideC); 
            Console.ReadLine();
        }

【讨论】:

  • 这就是诀窍。我的错误在于双方的分配。非常感谢您的帮助!
  • 或尝试“为 B 面输入小数”;)
【解决方案3】:
static decimal RequestDecimal(string message)
{
    decimal result;
    do 
    {
         Console.WriteLine(message);
    }
    while (!decimal.TryParse(Console.ReadLine(), out result));
    return result;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多