显示输入中三个数字的总和,并在同一行显示三个数字

时间:2015-09-18 06:57:41

标签: c# console line addition

int sum;
int display;               

Console.Write("Enter three whole numbers:" );

display = int.Parse(Console.ReadLine());
Console.Write(display);
Console.ReadKey();

如何计算总和以及显示我在同一行输入的数字?例如:输入:123解决方案:123 = 6

4 个答案:

答案 0 :(得分:2)

string input = Console.ReadLine();
sum = input.ToCharArray().Select(x => int.Parse(x)).Sum();

您可以使用TryParse并在安全网中构建,使其更加强大,但这取决于您。

答案 1 :(得分:2)

您的问题令人困惑,您正在提示用户输入Enter three whole numbers:,在您的示例中,您已将123作为输入。是否是三个整数?没有。如果问题描述了您的需要,那么您必须编写如下代码:

int a,b,c,sum;          
Console.Write("Enter three whole numbers:" );
a= int.Parse(Console.ReadLine());
b= int.Parse(Console.ReadLine());
c= int.Parse(Console.ReadLine());
sum=a+b+c;
Console.Write("sum={0}",sum);
Console.ReadKey();

如果示例中描述了需求,则应更改代码,如下所示:

 Console.Write("Enter three whole numbers:" );
 int sum= Console.ReadLine().Sum(c => c - '0');
 Console.Write("sum={0}",sum);

答案 2 :(得分:2)

那么,您希望用户如何输入123456? 由于123456可以以不同的方式阅读,例如1 234 56? 我宁愿

  Console.Write("Enter integer numbers to sum up, separating them by comma"):

  int result = Console
    .ReadLine()
    .Split(',')
    .Select(item => int.Parse(item)) 
    .Sum();

  // test: 123, 45, 67 => 235
  Console.Write(result);
  Console.ReadKey();

如果您想要总结给定字符串

中的所有数字
Console.Write("Enter the numbers which digits you want to sum up"):

String source = Console.ReadLine();

int result = source
  .Select(item => item - '0')
  .Sum();

// test: 12345 => "12345 = 15" since (1 + 2 + 3 + 4 + 5 = 15)
Console.Write(String.Format("{0} = {1}", source, result));
Console.ReadKey(); 

答案 3 :(得分:1)

string str = Console.ReadLine();
sum = SumOf(str);

public static int SumOf(string s) 
{
    int sum = 0;
    foreach (char num in s.ToCharArray())
    {
        sum += (int)char.GetNumericValue(num);
    }
    return sum;
}

与您的代码一起使用:

int display = 0;               

Console.Write("Enter three whole numbers:" );

string s = Console.ReadLine();
foreach (char num in s.ToCharArray())
{
    display += (int)char.GetNumericValue(num);
}
Console.Write("Sum of " + s + " = " + display);
Console.ReadKey();