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

Display Sum of three numbers from input and display the three numbers on the same line

int sum;
int display;               

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

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

如何在计算总和的同时显示我在同一行输入的数字? Eg.input : 123 解 : 123 = 6

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

您可以通过使用 TryParse 并构建安全网来使其更加稳健,但这取决于您。

您的问题令人困惑,您提示用户输入 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);

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

  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(); 
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();