Simply use the TryParse which converts a string
to a number double
, the first parameter of the method is the string to be converted and the second is the result in double
equivalent to the first parameter.
See the example adapted to your case:
var valores = ReadLine().Split(' ');
if (double.TryParse(valores[0], out var r1) && double.TryParse(valores[1], out var r2) && double.TryParse(valores[2], out var r3))
{
WriteLine($"{r1} {r2} {r3}");
}
Also, there is no need to worry about exceptions, it returns false if conversion fails, and true if successful.
Now your modified code would look like this:
var valores = ReadLine().Split(' ');
if (double.TryParse(valores[0], out var a) && double.TryParse(valores[1], out var b) && double.TryParse(valores[2], out var c))
{
double x1, x2;
double delta = b * b - 4 * a * c;
WriteLine($"Delta: {delta}");
}
Entry:
2 12 1.1
Output:
Delta: 135.2
See working at .NET Fiddle .
Issue
Return all the code, I think you meant to change the flow of program execution. For this case, you can use a loop.
There are many things that can be improved in the code below, I used as an illustration:
public static void Main() {
var loop = true;
do {
var valores = ReadLine().Split(' ');
if (valores.Length == 3) {
if (double.TryParse(valores[0], out var a) &&
double.TryParse(valores[1], out var b) &&
double.TryParse(valores[2], out var c)) {
double x1, x2;
double delta = b * b - 4 * a * c;
WriteLine($"\n\nDelta: {delta}");
loop = false;
}
else {
WriteLine("\nValores invalidos.\n");
}
}
else {
WriteLine("\nQuantidade de parametros invalidos. Informe 3 parametros.\n");
}
} while (loop);
}
In the example I used do-while
, it runs at least once, other than while
, which can be executed zero or more times. The boolean variable loop
indicates the stop condition of the program, when false the program exits the loop while
and ends. Since we are using a vector it is necessary to check if the indexes are valid for not throwing an exception, we check
if (valores.Length == 3) { ...
for three elements.
See all the code working in .NET Fiddle .