读书人

c#交换排序 找不到异常 求高手改改

发布时间: 2013-08-04 18:26:16 作者: rapoo

c#交换排序 找不到错误 求高手改改
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TextHello
{
class Program
{
static void Main(string[] args)
{
int i, j = 0;
int[] a = { 1, 2, 4, 5, 3 };
for (i = 0; i < 5; i++)
{
int temp;
while (j < 5)
{
if (a[i] > a[i + 1])
{
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
j++;

}
}

}
for (int x = 0; x < 5; x++)
{
System.Console.WriteLine("第{0}个元素是{1}", x + 1, a[x]);
}


}
}
}
新手写个程序 试试 ,调试进行不下去,不知道哪里出问题 C# 调试
[解决办法]
while (j < 5)
{
if (a[i] > a[i + 1])
{
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
j++;

}
}
你这里有问题,这个循环在i那个循环里面,你while了j 5次,但是里面的i始终是同样的。
而且当i=1的时候j已经是5了后面的就都比不了了。
作用域问题。

[解决办法]
你要达到什么样的效果的?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int i, j = 0;
int[] a = { 1, 2, 4, 5, 3 };


for (i = 0; i < 4; i++)
{
int temp;
for (j = 0; j < 5;j++ )
{
if (a[i] > a[i + 1])
{
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
j++;

}
}

}
for (int x = 0; x < 5; x++)
{
System.Console.WriteLine("第{0}个元素是{1}", x + 1, a[x]);
}
Console.ReadLine();
}
}
}
看看符合你的要求不
[解决办法]


namespace TextHello
{
class Program
{
static void Main(string[] args)
{
int[] a = { 1, 4, 1, 3, 5 };


for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 4 - i; j++)
{
if (a[j] > a[j + 1])
{
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
for (int x = 0; x < 5; x++)
{
Console.Write(string.Format("第{0}个元素是{1}", x+1, a[x]));
}
Console.ReadLine();
}
}
}


[解决办法]
引用:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace paixuesuanfa
{
class Program
{
static void Main(string[] args)
{
int[] a = { 5, 4, 3, 2, 1 };


for (int j = 0; j < 5; j++)
for (int i = 0; i < 4; i++)
if (a[i] > a[i + 1])
{
int temp;
temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp;//

}
for (int x = 0; x < 5; x++)
{
System.Console.WriteLine("第{0}个元素是{1}", x + 1, a[x]);
}
}
}
}
最后修改好的 输出12345



or (int i = 0; i < 4; i++) ==> or (int i = 0; i < 4-j; i++)

读书人网 >C#

热点推荐