首页 > 解决方案 > 在数组的整数元素中搜索一个数字

问题描述

在数组的整数元素中搜索“幻数”,并对包含“幻数”的所有整数求和。

例如 :

1, 2, 3, 4, 5, 55 和幻数是 5

1, 2, 3, 4, 5, 55 包含神奇数字“5”的数字之和为:60


(提前感谢您的帮助)到目前为止我有:

       int[] arrayOfUserInput = new int[10];
       int i;

        //------------------------------- Array and variable declaration

        Console.WriteLine("Please enter 10 integers : ");
        for (i = 0; i < 10; i++)
        {
            Console.Write("array element = {0} : ", i);
            arrayOfUserInput[i] = Convert.ToInt32(Console.ReadLine());
        }
        //-------------------------------- User input of 10 integers


        Console.Write("Please enter your magic number : ");
        int magicNumberInput = Convert.ToInt32(Console.ReadLine());

        if (magicNumberInput >= 0 && magicNumberInput <= 9)
        {
            Console.WriteLine($"Your magic number is : {magicNumberInput}");
        }
        else
        {
            Console.WriteLine("Sorry, but please enter single digit number!");
        }

        //-------------------------------- User input & displaying of magic number

        Console.WriteLine("Your integers are : ");
        for (i = 0; i < 10; i++)
        {
        Console.Write("{0}  ", arrayOfUserInput[i]);
        }
        Console.WriteLine("");

        //--------------------------------- Displaying user input of 10 integers

标签: c#

解决方案


您可以使用 Linq.Where().Sum()计算包含幻数的所有数字的总和。

using System;
using System.Linq;
using System.Collections.Generic;

...

var arrayOfUserInput = new int[] {1, 2, 3, 4, 5, 55};
var magicNumberInput = 5;

var sumOfNumbers = arrayOfUserInput
    .Where(x => x.ToString().Contains(magicNumberInput.ToString()))  //Filter by Magic numbers
    .Sum();                                             //Calculate sum of filtered numbers.

.Net 小提琴


如果您不想使用 Linq,那么您可以使用foreachfor循环使用string.Contains()函数。

...
var sumOfNumbers = 0;
foreach(var input in arrayOfUserInput)
{
     if(input.ToString().Contains(magicNumberInput.ToString()))
          sumOfNumbers += input;
}

Console.WriteLine(sumOfNumbers);

我强烈建议您阅读有关LINQ和 C# 基础知识的更多信息。


代码重构说明:

如果您以字符串格式存储输入数据,则无需再次将其转换为字符串。在添加时将其转换为int并添加到sumOfNumbers. 喜欢,

使用 Linq,

 var sumOfNumbers = arrayOfUserInput
     .Select(x => x.Contains(magicNumberInput) && int.TryParse(x, out int number) ? number : 0)
    .Sum();  

使用 for 循环,

...
var sumOfNumbers = 0;
foreach(var input in arrayOfUserInput)
{
     if(input.Contains(magicNumberInput) && int.TryParse(input, out int number))
          sumOfNumbers += number;
}

推荐阅读