首页 > 解决方案 > 用逗号打印偶数,除了 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]);
                    }
                }
            }
        }
    }
}

提前致谢 :)

标签: c#arraysiteration

解决方案


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)));

推荐阅读