我是C#的新手,正在try 解决以下问题:

Write a program in C# to find the sum of all elements of the array. Go to the editor
Test Data:

Input the number of elements to be stored in the array: 3
Input 3 elements in the array:
element - 0: 2
element - 1: 5
element - 2: 8

预期输出:

Sum of all elements stored in the array is: 15

以下是我想出的解决方案:

Console.Write("Enter the length of the array : ");
int len = Convert.ToInt32 (Console.ReadLine());
int[] arr = new int[len];
for (int i = 0; i < len; i++) {
    arr[i] = Convert.ToInt32(Console.Read());
}
Console.WriteLine(arr.Sum());

But I am getting the following outputs:
1

有人能告诉我我做错了什么吗?

推荐答案

try 将Console.Read更改为Console.ReadLine并直接使用int.Parse:

for (int ii = 0; ii < len; ii++) {
    arr[ii] = int.Parse(Console.ReadLine());
}

然后在不同的行上输入数字(请注意,通常建议使用int.TryParse来验证输入,因为如果字符串无法解析为数字,则int.Parse将抛出).

Console.Read已返回int,即:

输入流中的下一个字符,如果当前没有要读取的字符,则返回负数(-1).

它表示编码的字符(包括空格、字母等)值.即,如果您输入1,您将得到49作为结果(例如,try Console.WriteLine((int)'1')).

Csharp相关问答推荐

自定义JsonEditor,用于将SON序列化为抽象类

在Dapper中使用IasyncEum重写GetAsyncEum方法

处理. netstandard2.0项目中HttpClient.SslProtocol的PlatformNotSupportedException问题""

是否可以使用EF—Core进行临时部分更新?

实体框架核心上是否支持使用NPGSQL的字符串聚合?

将现有字段映射到EFCore中的复杂类型

C# CompareTo()和Compare()可以返回除-1和1以外的整数吗?

如何在C#中创建VS代码中的控制台应用程序时自动生成Main方法

EF核心新验证属性`DeniedValues`和`StringCompison`不起作用

在两个已具有一对多关系的表之间添加另一个一对多关系

.NET Google Workspace API获取错误CS0266

解决方案:延长ABP框架和ANGING OpenIddict中的令牌生命周期

C#无法将.csv列转换为用于JSON转换的列表

Maui:更改代码中的绑定字符串不会更新UI,除非重新生成字符串(MVVM)

如何在绑定到数据库的datagridview中向上或向下移动行

当要删除的子模型没有父模型的1:多属性时,如何告诉实体框架设置1:1 FK条目?

如何为控制器PUT操作绑定对象数组

在使用.NET EF Core DbContext属性之前,是否应使用null判断

C#If条件格式

我应该使用IMhemyCache来存储承载令牌,还是应该为Azure函数中的401个错误实施Polly重试策略?