简体   繁体   English

C#,将String转换为double的最佳方法是什么?

[英]C# , What is the best way of converting a String to a double?

I've been looking at already answered solutions to this questions but none of them seem to work with my code. 我一直在寻找对此问题已经回答的解决方案,但是似乎没有一个与我的代码兼容。 I've only just started coding in C# and I'm confused how my code isn't working. 我才刚刚开始用C#编写代码,我很困惑我的代码是如何工作的。

using System;

namespace dt
{
  class Averager 
  {
    static void Main() 
    {
      var total = 0.0;
      int runningNumbers = 0;

      while(true) 
      {
        Console.Write("Enter a number or type \"done\" to see the average: ");

        if(Console.ReadLine().ToLower() == "done") 
        {
          var average = (total / runningNumbers);
          Console.Write("Average: " + average);
          break;
        }
        else 
        {
          var tempNew = Double.Parse(Console.ReadLine());
          total += tempNew;
          runningNumbers += 1;
          continue;
        }

      }
    }
  }
}

In my code above, I'm trying to convert an inputted string to a double. 在上面的代码中,我试图将输入的字符串转换为双精度型。 When I run the program, it loops once and the the program freezes. 当我运行该程序时,它循环一次,并且程序冻结。 If I type in the console, it gives me this error: 如果我在控制台中键入,则会出现此错误:

Unhandled Exception: 未处理的异常:

System.FormatException: Input string was not in a correct format. System.FormatException:输入字符串的格式不正确。
at System.Number.ParseDouble (System.String value, System.Globalization.NumberStyles options, System.Globaliz 在System.Number.ParseDouble(System.String值,System.Globalization.NumberStyles选项,System.Globaliz
at System.Double.Parse (System.String s, System.Globalization.NumberStyles style, System.Globalization.Number 在System.Double.Parse(System.String s,System.Globalization.NumberStyles样式,System.Globalization.Number
at System.Double.Parse (System.String s, System.IFormatProvider provider) [0x0000c] in at dturato.Averager.Main () [0x00058] in <249eeff07c4a4744a6b024a0c9b6c23b>:0 在System.Double.Parse(System.String s,System.IFormatProvider提供程序)处[0x0000c]在dturato.Averager.Main()中的[0x00058]在<249eeff07c4a4744a6b024a0c9b6c23b>:0中
[ERROR] FATAL UNHANDLED EXCEPTION: System.FormatException: Input string was not in a correct format. [错误]致命异常:System.FormatException:输入字符串的格式不正确。
at System.Number.ParseDouble (System.String value, System.Globalization.NumberStyles options, System.Globaliz 在System.Number.ParseDouble(System.String值,System.Globalization.NumberStyles选项,System.Globaliz
at System.Double.Parse (System.String s, System.Globalization.NumberStyles style, System.Globalization.Number 在System.Double.Parse(System.String s,System.Globalization.NumberStyles样式,System.Globalization.Number
at System.Double.Parse (System.String s, System.IFormatProvider provider) [0x0000c] in at d.Averager.Main () [0x00058] in <249eeff07c4a4744a6b024a0c9b6c23b>:0** 在System.Double.Parse(System.String s,System.IFormatProvider提供程序)处[0x0000c]在d.Averager.Main()中的[0x00058]在<249eeff07c4a4744a6b024a0c9b6c23b>:0 **中

This , from what I've researched so far, means the String isn't converting to a double for some reason. 根据我到目前为止的研究,这意味着String由于某种原因没有转换为double。 If anyone could help or give any solutions that would be great, thanks. 如果有人可以帮助或提供任何出色的解决方案,谢谢。

You're calling ReadLine twice! 您要两次致电ReadLine The first time is after the prompt. 第一次是在提示后。 The second is in the else clause of your if statement. 第二个是在if语句的else子句中。 The second one is likely null and causes the error when trying to convert to double. 第二个可能为null,并在尝试转换为double时导致错误。 You need to store the value of your input to a variable: 您需要将输入的值存储到变量中:

using System;

namespace dt
{
  class Averager 
  {
    static void Main() 
    {
      var total = 0.0;
      int runningNumbers = 0;

      while(true) 
      {
        Console.Write("Enter a number or type \"done\" to see the average: ");
        string input = Console.ReadLine();

        if(input.ToLower() == "done") 
        {
          var average = (total / runningNumbers);
          Console.Write("Average: " + average);
          break;
        }
        else 
        {
          var tempNew = Double.Parse(input);
          total += tempNew;
          runningNumbers += 1;
          continue;
        }

      }
    }
  }
}

The error tells you the exact problem you're having. 该错误告诉您确切的问题。

Input string was not in a correct format. 输入的字符串格式不正确。

You need to make sure the input into the parse method is valid. 您需要确保对parse方法的输入有效。 In most cases, you will find a TryParse variant of the Parse methods. 在大多数情况下,您会发现Parse方法的TryParse变体。 In this case, double.TryParse does just that. 在这种情况下, double.TryParse就是这样做的。

using System;

public class Example
{
   public static void Main()
   {
      string value;
      double number;

      value = Double.MinValue.ToString();
      if (Double.TryParse(value, out number))
         Console.WriteLine(number);
      else
         Console.WriteLine("{0} is outside the range of a Double.", 
                           value);

      value = Double.MaxValue.ToString();
      if (Double.TryParse(value, out number))
         Console.WriteLine(number);
      else
         Console.WriteLine("{0} is outside the range of a Double.",
                           value);
   }
}
// The example displays the following output:
//    -1.79769313486232E+308 is outside the range of the Double type.
//    1.79769313486232E+308 is outside the range of the Double type.   

To reference back to you code, you're initial problem is you're reading the input multiple times: Try this 为了回想您的代码,您最初遇到的问题是要多次读取输入:

using System;

namespace dt
{
  class Averager 
  {
    static void Main() 
    {
      var total = 0.0;
      int runningNumbers = 0;

      while (true)
        {
            // Ask for user for a new input
            Console.Write("Enter a number or type \"done\" to see the average: ");
            var line = Console.ReadLine();

            // Try to parse the input
            double value;
            if(double.TryParse(line, out value)) {
                total += value;
                runningNumbers += 1;
                continue;
            } else if(line.ToLower() == "done")
            {
                var average = (total / runningNumbers);
                Console.Write("Average: " + average);
                break;
            } else {
                Console.Write("Invalid input. Please try again.");
                continue;
            }

        }
    }
  }
}

I would just stuff it into a double right off the bat -- using "Convert.toDouble(yourValue). It appread that you are already doing your checking to see if you will be getting a numeric value or a string so why not skip the var and make it a double straight away? 我只是马上将其填充为双精度-使用“ Convert.toDouble(yourValue)。它表明您已经在进行检查,看是否要获取数字值或字符串,所以为什么不跳过var并使其立即变倍?

using System; 使用系统;

 namespace dt{
    class Averager
        static void Main(){
  var total = 0.0;
  int runningNumbers = 0;

  while(true) 
  {
    Console.Write("Enter a number or type \"done\" to see the average: ");
    var test = Console.Readline();
    if(test.ToLower() == "done") 
    {
      var average = (total / runningNumbers);
      Console.Write("Average: " + average);
      break;
    }
    else 
    {
      double tempNew = Convert.toDouble(test);
      total += tempNew;
      runningNumbers += 1;
      continue;
    }

   }
  }
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM