c# - 在数组的整数元素中搜索一个数字
问题描述
在数组的整数元素中搜索“幻数”,并对包含“幻数”的所有整数求和。
例如 :
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
解决方案
您可以使用 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.
如果您不想使用 Linq,那么您可以使用foreach
或for
循环使用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;
}
推荐阅读
- css - 如何为具有多个配置选项的 WordPress 插件解决 CSS
- python - pd.pivot:整齐到宽数据帧转换错误
- python - Python,Pandas Dataframe,列,其中包含前面所有内容的总和,并为 df 中的新项目重新开始
- kubernetes - 调用 webhook 失败“namespace.sidecar-injector.istio.io”
- android - 自定义布局 Android Compose 可测量宽度
- python - 为什么 sqlalchemy 声明性基础对象没有属性“查询”?
- javascript - 检查数组中的日期是否包含晚于当前日期的日期
- python - 如何将向量分离为基向量?
- flutter - 在 Flutter 中实现时 Listview.builder 不显示我的图像
- c# - 取消订阅委托与函数中的事件