+ 1
How to identify different value types in the same line of code
For example,I input "3.1+4.8" in console.It can identify double type value 3.1 and 4.8,and char type value'+'.Than console will output 7.9 by adding 3.1 to 4.8. I wish there exist some kind of simple method since i'm a biginner.
4 Réponses
+ 1
It all depends on what is written on the line of code.
First of all, it is important to note that "+" is an operator and not a char value. That´s why the code performs the calculation.
However on your example you wouldn't get that result because Console.ReadLine() is a method that always returns a string. And C# is very rigid about types.
So in that case you would get a string with the value: "3.1+4.8" in it.
In order to actually do such operation you would have to convert the result of Console.ReadLine() to a double using a method like "double.Parse()" or "Convert.ToDouble()". Then you could assign those values to two variables(declaring the type "double" on them) and then perform the calculation.
You could use this piece of code to see how it works. Just copy and paste inside the curly brackets "{ ... }" of the Main function on your C# file:
double a = double.Parse(Console.ReadLine());
Console.WriteLine("Your first double is " + a);
double b = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Your second double is " + b);
double sum = a + b;
Console.WriteLine("The result is: "+ sum);
Console.ReadLine();
Hope this helped.
+ 1
Oh! Now I guess I got exactly what you want!!!
Try this one. Just copy and paste inside the curly brackets "{ ... }" of the Main function on your C# file:
string userInput = Console.ReadLine();
string[] operador = { "+" };
string[] individualInputs = userInput.Split(operador, StringSplitOptions.RemoveEmptyEntries);
float result = 0;
foreach (string member in individualInputs)
{
result += float.Parse(member);
}
Console.WriteLine(result);
Console.ReadLine();
Now you can enter as many floats as you want, as long as they follow the same formula of your given exemple "3.1+4.8". Then the program will sum them all and output. For instance, this "4.1+2.5+1.2+2.2" should work too.
Just be careful, if you accidentally insert empty spaces like "2.0 + 1.2" you'll get a compile error. But just go with the formula "2.0+1.2" and you'll be just fine.
Hope this helped a little bit more. :)
+ 1
Thank you very much,your code helped me a lot!
0
Thank you very much,I understand what you talked about.However,I'm still confused.
Follow your word,I need to put value in three different lines.One for'3.1',one for'+',one for'4.8',which means I have to push the "Enter" button twice.
And know I want to skip these steps.
So I wish I can input these value to one line as string value.Than console can identify them one by one,and plus finally.
Of course,it's fine that we can't make that fundation possible,we can get them from several lines.