我正在尝试让这个程序让我输入所需的数字(条目),然后为这些条目输入所需的值。它应该写出最大值(绿色),最小值(红色)然后是序列的其余部分。在下一行中,最大和最小应该改变位置(甚至没有为此输入代码)。我做错了什么(特别是在最后'for loop'中)
int max = int.MinValue;
int min = int.MaxValue;
Console.WriteLine("How many numbers do you want to enter ? ");
int kolicinaBrojeva = int.Parse(Console.ReadLine());
int[] niz = new int[kolicinaBrojeva];
for (int i = 0; i < kolicinaBrojeva; i++)
{
Console.WriteLine("Enter {0}. a number:", i + 1);
niz[i] = int.Parse(Console.ReadLine());
if (niz[i] > max)
{
max = niz[i];
}
if (niz[i] < min)
{
min = niz[i];
}
}
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(max + ", ");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(min + ", ");
Console.ResetColor();
for (int i = 1; i >= 0; i--)
{
if (niz[i] < max && niz[i] > min)
{
Console.Write(niz[i] + ", ");
}
}
答案 0 :(得分:2)
最后一个for循环应如下所示:
@Mtest. @Ba @Yis @GThis
答案 1 :(得分:0)
您当前的代码将正确读取kolicinaBrojeva数字,但最小值和最大值将无法正确设置。没有其他int大于int.MaxValue,同样,没有其他int小于int.MinValue。你可以改为:
int max = int.MinValue;
int min = int.MaxValue;
有了这个,你将得到正确的最小值和最大值,但是,我不确定你在最后一个循环中想要做什么。
答案 2 :(得分:0)
试试这个。
using System;
class Test
{
static void Main()
{
string[] temp = Console.ReadLine().Split();
int[] numbers = new int[temp.Length];
for (var i = 0; i < numbers.Length; i++)
numbers[i] = int.Parse(temp[i]);
int minIndex = 0;
int maxIndex = 0;
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] < numbers[minIndex])
minIndex = i;
if (numbers[i] > numbers[maxIndex])
maxIndex = i;
}
Swap(ref numbers[maxIndex], ref numbers[0]);
Swap(ref numbers[minIndex], ref numbers[numbers.Length - 1]);
Print(numbers, ConsoleColor.Green, ConsoleColor.Red);
Swap(ref numbers[0], ref numbers[numbers.Length - 1]);
Print(numbers, ConsoleColor.Red, ConsoleColor.Green);
}
static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
static void Print(int[] array, ConsoleColor a, ConsoleColor b)
{
Console.ForegroundColor = a;
Console.Write(array[0] + " ");
Console.ResetColor();
for (int i = 1; i < array.Length - 1; i++)
Console.Write(array[i] + " ");
Console.ForegroundColor = b;
Console.WriteLine(array[array.Length - 1]);
Console.ResetColor();
}
}