0

i have a serious problem in C# console application, the following code doesn't work as what i want... it must ask me to type the following letters value, then it must calculate with the values i typed, but when i type a character such as 'x', it doesn't make it equivalent to "1", how can i solve that problem???, what is the certain solution?? "x" value should be equivalent to 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!");

        }
8
  • 2
    How would you compare a double to a char? Commented Sep 8, 2013 at 18:01
  • Why not type 1 instead of x? Your code shows that you want to allow user to enter number not any non-numeric string. Commented Sep 8, 2013 at 18:02
  • i am trouble in type conversions :) Commented Sep 8, 2013 at 18:03
  • How can you expect a double be equal to x . double a = Convert.ToInt32(Console.ReadLine()); if (a=='x') Commented Sep 8, 2013 at 18:03
  • king king that's actual problem for me, how can i solve it ?? Commented Sep 8, 2013 at 18:04

1 Answer 1

1

You can do like this:

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

NOTE: the code doesn't care about some conversion exception, you should use try-catch to deal with it.

Sign up to request clarification or add additional context in comments.

4 Comments

I think, with the info we have, this the best solution. But i really can't understand what OP want to attain.
problem solved, thats really easy, but it didnt come to my mind ;) thanks a lot
trycatch is not optimal. You could use int.TryParse. For example: int a; if (s == "x") { a = 1; } else if (!int.TryParse(s, out a)) { /* handle wrong input */ }
@JeppeStigNielsen it's even better to prevent user from typing any non-numeric character, don't need to use any try-catch, or TryParse.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.