Simply use the method Tryparse that converts a string
for 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 the conversion fails, and true if it succeeds.
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}");
}
Entree:
2 12 1.1
Exit:
Delta: 135.2
See working on .NET Fiddle.
Editing
Return all the code, I think you meant to change the execution flow of the program. For this case, you can use a loop.
There are many things that can be improved in the code below, I used as 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 the do-while
, it is executed at least once, different from the while
which can be run zero or more times. The boolean variable loop
indicates the program stop condition, when it is false the program leaves the loop while
and finish. Since we are using a vector it is necessary to verify that the indexes are valid not to launch an exception, we check in
if (valores.Length == 3) { ...
for three elements.
See all the code working on .NET Fiddle.
Are you saying to check if the variables reported in Bhaskara or if they were not defined in the Runtime?
– CypherPotato
Check that they have not been given by the user in Runtime
– PLINIO RODRIGUES
good logic is five variables that must be informed, correct? if data does not have 5 positions the data has not been informed and if even informed are not certain is also another problem, it would not be more logical to put a repetition structure to solve this problem?
– novic
Actually there are 3 variables a, b and c, the others I just declared them as double. How can I make a repeat loop to check if the a, b and c were not informed ? I started programming in C# for now.
– PLINIO RODRIGUES