Skip to main content
 首页 » 编程设计

c#之在 C# 中检查用户输入

2024年02月13日11sxdcgaq8080

我刚刚编写了我的第一个 C# 控制台应用程序,我还是一个初学者。无论如何,我尝试了下面的代码并且它似乎有效,它用于求解二次方程。我想为用户输入字符串而不是整数的情况添加代码,并给出错误消息关于如何实现它的任何想法?

namespace Quadratic_equation 
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            Console.WriteLine("welcome to seyi's quadratic calculator!!!"); 
            Console.Write("a:"); 
            double a = Convert.ToInt32(Console.ReadLine()); 
 
 
            Console.Write("b:"); 
            double b = Convert.ToInt32(Console.ReadLine()); 
            Console.Write("c:"); 
            double c = Convert.ToInt32(Console.ReadLine()); 
            if ((b * b - 4 * a * c) < 0) { 
                Console.WriteLine("There are no real roots!"); 
            } 
            else { 
                double x1 = (-b + Math.Sqrt((b*b)-4*a*c)) /2*a; 
                double x2 = (-b + Math.Sqrt((b*b)-4*a*c)) /2*a; 
                Console.WriteLine("x:{0}",x1); 
                Console.WriteLine("y:{0}",x2); 
            } 
 
            Console.ReadKey(); 
        } 
    } 
} 

请您参考如下方法:

您可以使用 Int32.TryParse method检查您的字符串是否是有效整数。此方法返回一个 boolean 值,表示您的对话是否成功。

Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.

而且我不明白为什么要将 Convert.ToInt32 的返回值保留为 double方法。这些因子(a、b、c)应该是整数,而不是 double 。

int a; 
string s = Console.ReadLine(); 
if(Int32.TryParse(s, out a)) 
{ 
   // Your input string is a valid integer. 
} 
else 
{ 
  // Your input string is not a valid integer. 
} 

这个 Int32.TryParse(string, out int) 重载使用 NumberStyle.Integer作为默认值。这意味着您的字符串可以包含其中之一;

  • 尾随空格
  • 前导空格
  • 前导符号