【问题标题】:Using String Type in Integer Type?在整数类型中使用字符串类型?
【发布时间】:2013-09-08 18:00:07
【问题描述】:

我在 C# 控制台应用程序中有一个严重的问题,下面的代码不能按我想要的那样工作......它必须要求我输入以下字母值,然后它必须用我输入的值进行计算,但是当我输入了一个字符,例如'x',它并不等同于“1”,我该如何解决这个问题???,确定解决方案?? “x”值应等于 1

string nun = "2";
        Console.WriteLine("Type the 'A' value");
        double a = Convert.ToInt32(Console.ReadLine());

        if (a=='x') {

            a = 1

        }
        Console.WriteLine("Type the 'B' value");
        double b = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("Type the 'C' value");
        double c = Convert.ToInt32(Console.ReadLine());


        double delta = Math.Pow(b,2) - (4*a*c);


        if(delta > 0 ) {

            double x1 = (-b + Math.Sqrt(delta) / 2 * a);
            Console.WriteLine("value of x1: {0}",Convert.ToInt32(x1));
            double x2 = (-b - Math.Sqrt(delta) / 2 * a);


            Console.WriteLine("value of x2: {0}",Convert.ToInt32(x2));
        }

        else if (delta < 0) {

            Console.WriteLine("there is no any different real root in this equation!");

        }

【问题讨论】:

  • 如何比较 double 和 char?
  • 为什么不输入1 而不是x?您的代码显示您希望允许用户输入 number 而不是任何非数字字符串。
  • 我在类型转换方面遇到了麻烦 :)
  • 你怎么能期望 double 等于 xdouble a = Convert.ToInt32(Console.ReadLine()); if (a=='x')
  • 王者王这对我来说是个实际问题,我该如何解决??

标签: c# string int


【解决方案1】:

你可以这样做:

    Console.WriteLine("Type the 'A' value");
    string s = Console.ReadLine();        
    double a = s == "x" ? 1 : Convert.ToInt32(s);

注意:代码不关心一些转换异常,你应该使用try-catch来处理它。

【讨论】:

  • 我认为,根据我们掌握的信息,这是最好的解决方案。但我真的无法理解 OP 想要达到的目标。
  • 问题解决了,这很容易,但我没有想到 ;) 非常感谢
  • trycatch 不是最优的。你可以使用int.TryParse。例如:int a; if (s == "x") { a = 1; } else if (!int.TryParse(s, out a)) { /* handle wrong input */ }
  • @JeppeStigNielsen 最好防止用户输入任何非数字字符,不需要使用任何try-catchTryParse
猜你喜欢
  • 1970-01-01
  • 2019-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-25
  • 2014-06-30
相关资源
最近更新 更多