C# 查找数组中给定的数字是偶数还是奇数#
有谁能解释一下为什么这不起作用,当我测试它的时候,我得到了很多随机的偶数和奇数输出C# 查找数组中给定的数字是偶数还是奇数#,c#,.net,C#,.net,有谁能解释一下为什么这不起作用,当我测试它的时候,我得到了很多随机的偶数和奇数输出 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication13 { class Program { static void Main(string[]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication13
{
class Program
{
static void Main(string[] args)
{
int[] array = new int[8] { 1, 2, 3, 4, 8, 5, 7, 9 };
int UserInput = 0;
start:
Console.WriteLine("Please enter a slot: ");
UserInput = Convert.ToInt32(Console.ReadLine());
if(array[UserInput]%2 == 0)
{
Console.WriteLine("Number is even");
}else
{
Console.WriteLine("Number is odd");
}
Console.ReadKey();
goto start;
}
}
}
我想输出数组中的单元格是偶数还是奇数,而不是输入的数字,所以如果输入了数字5,它应该输出,即使单元格5包含数字8 数组在C#中是基于0的,因此需要从用户输入中减去1。此外,您还需要添加一些检查逻辑,以确保它们输入的值不高于8或小于1
if (UserInput < 1 || UserInput > 8)
{
Console.WriteLine("Please enter a number between 1 and 8");
goto start;
}
else if(array[UserInput - 1] % 2 == 0)
{
Console.WriteLine("Number is even");
}else
{
Console.WriteLine("Number is odd");
}
if(UserInput<1 | | UserInput>8)
{
Console.WriteLine(“请输入一个介于1和8之间的数字”);
转到开始;
}
else if(数组[UserInput-1]%2==0)
{
Console.WriteLine(“数字为偶数”);
}否则
{
控制台。WriteLine(“数字是奇数”);
}
数组索引计数从0开始,因此插槽“5”实际上是数字5,而不是8。实际上,单元格4(不是5)包含数字8。数组索引是从零开始的,因此数组[0]=1,数组[1]=2,依此类推。用户是否输入一个基于一的数字?如果是这样的话,你需要从用户输入中减去一才能得到你想要的索引吗?你是否尝试过将数组[UserInput]放入一个变量中,然后调试它或将其写入控制台以确保它正确地从数组中检索值?哦,天哪,我真是个白痴,我忘了这一点,我正在学习你看。感谢你清除了这个错误,有时候你只需要第二副眼睛:)我喜欢用额外的if语句为数组大小之外输入的值做防白痴的主意,我打算添加一个额外的输出,说输入值在1到8之间,但让代码不可破解总是好的,再次感谢你