c# - 用逗号打印偶数,除了 C# 中的最后一个不工作
问题描述
几天来,我一直在尝试解决此问题,但找不到错误。它似乎就像一个 if 语句一样简单,代码可以打印除最后一个数字以外的所有数字的逗号。它对我输入随机数很有用,但是当我输入特定数字(24、7、35、2、27、7、89)时,它会在末尾打印逗号。
这是我的代码,但我尝试了多种其他方式。
using System.Collections.Generic;
using System.Text;
using System.Transactions;
namespace ArrayExercises
{
class TaskFour
{
public static void FindEvenNumbers()
{
int[] input = new int[7];
int count = 1;
string comma = ",";
Console.WriteLine("[== Please Enter 7 numbers ==]");
Console.WriteLine();
for (int i = 0; i < input.Length; i++)
{
Console.WriteLine($"Enter number {count}:");
input[i] = int.Parse(Console.ReadLine());
count++;
}
Console.WriteLine("The even numbers in this array are: ");
for (int i = 0; i < input.Length; i++)
{
if (input[i] % 2 == 0)
{
if (i < input.Length)
{
Console.Write(input[i] + comma);
}
else
{
Console.Write(input[i]);
}
}
}
}
}
}
提前致谢 :)
解决方案
for
您可以使用下面的代码,而无需使用循环引入任何额外空间。
for (int i = 0; i < input.Length; i++)
{
if (input[i] % 2 == 0)
{
if (i != 0) Console.Write(comma);
Console.Write(input[i]);
}
}
或者使用内置string.Join
功能。
Console.WriteLine(string.Join(',', input.Where(i => i % 2 == 0)));
推荐阅读
- dart - 使用 AsyncSnapshot 时,相同的对象不相等并且具有不同的 identityHashCode 输出
- javascript - 在包含循环和 2 种不同显示方式的页面上使用 Pym.js
- azure-ad-b2c - How do I get the claim details from Azure B2C Angular app if I use MSAL 2.0 & PKCE
- tensorflow - How to make Federated Learning datasets 'tff.simulation.datasets.emnist' from LEAF and NIST?
- python - How do I implement proper inter process comunication in this system?
- time-series - Should I do statistical test in other time-series features to check stationary?
- performance - Parallel benchmarks on coda and map reduce function
- python - Django:特定的 unique_together 条件
- ios - 无法使用 cargo lipo --release 构建库
- javascript - Capybara 不选择没有 JavaScript 的单选按钮