Naru Lopo
Naru Lopo

Reputation: 19

C# How I can make a sum wih Console.Readline

The idea that I have is:

I tried Console.WriteLine("sum: {0}",Console.Readline()); I could upload a image with the idea if this it's not enought sorry for my english.

Upvotes: 0

Views: 1247

Answers (2)

Daniel Manta
Daniel Manta

Reputation: 6683

int sum = 0;
var values = new Dictionary<string, int>
{
    { "a", 1 },
    { "b", 2 },
    { "c", 3 }
};
var input = Console.ReadLine().Split('+');
foreach (string variable in input)
{
    sum += values.ContainsKey(variable) ? values[variable] : 0;
}
Console.WriteLine("Sum: {0}", sum);

For example:

a+b+c
Sum: 6

Upvotes: 2

RememberOfLife
RememberOfLife

Reputation: 106

Basic procedure if you only wanted to do additions: split the input string and then iterate through said output while adding all the numbers together. Output will be in string format so a cast must be supplied.

Full code:

string[] tmp_out = Console.ReadLine().Split('+');
int tmp_sum = 0;
foreach (string tmp_number in tmp_out)
{
    tmp_sum += int.Parse(tmp_number); // consider using TryParse if you are not sure if the input format is correct
}
Console.WriteLine("Sum=" + tmp_sum);

If you need further computing power, look into CSharpCorner

Upvotes: -1

Related Questions