c# - 将数组中的所有整数相乘
问题描述
我需要将给定数组中的所有整数乘以-1。我没有看到我在哪里犯了错误,但这是我到目前为止的代码:
public static int[] InvertValues(int[] input)
{
int x = -1;
foreach(int y in input)
{
x *= y;
}
return input;
}
解决方案
这是基于作者最初尝试的一种解决方案:
这会将每个单个元素乘以 -1。
您的错误是您需要访问数组的每个单独元素并通过索引将其写回。为此,您最好使用for
循环。
然后访问输入数组中的原始值,将其乘以 -1 并将其写回,从而覆盖输入数组中的原始值。
public static int[] InvertValues(int[] input)
{
for(int index = 0; index<input.Length;index++)
{
input[index] = input[index] * -1;
}
return input;
}
我会进行下一步,而不是更改原始输入数组并返回一个副本:
public static int[] InvertValues(int[] input)
{
int[] results = new int[input.Length]
for(int index = 0; index<input.Length;index++)
{
results [index] = -input[index]; //this flips the sign of the number, no need to do * -1
}
return results;
}
一个更好更短的选择:)
using System.Linq; //need to be added
//...
public static int[] InvertValues(int[] input)
{
return input.Select(x=> -x).ToArray();
}
推荐阅读
- r - 在 R 中隐藏未选择的 visNetwork 节点
- html - 我应该使用什么定位器来获取在 Selenium 中切换页面的元素列表?
- java - Activity 中的 LiveData、setValue 和片段中的观察。可能吗?
- android - google play 控制台无法识别打包在 android app bundle 文件 (.aab) 中的调试符号和映射文件
- javascript - Express Nodejs S3 上传到三个不同的目录
- r - 加载 ade4 和 adegenet 包时出现问题
- javascript - 错误“未捕获的类型错误:无法读取未定义的属性 'bannable'”
- r - 使用多组上限和下限创建置信区间比较图
- vue.js - vue 在点击时渲染组件
- c# - Blazor WebAssembly 应用程序 - Markdig - 无法在 Markdown 中呈现管道表或网格表