C#的问题,希望高手给解决下

来源:百度知道 编辑:UC知道 时间:2024/07/05 03:05:55
今天在写一个数字排列顺序的时候,发现一个问题!
原代码是
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
int[] list ={1,0,9,2,8,3,7,4,6,5};
Console.WriteLine("排序前:");
for (int i = 0; i < list.Length; i++)
Console.WriteLine(list[i]);
Console.WriteLine();
int tmp = 0;
bool p = false;
while(!p)
{
p = true;
for(int i=0;i<list.Length-1;i++)
{
if(list[i]>list[i+1])
{
tmp=list[i];
list[i]=list[i+1];
list[i+1]=tmp;
p = false;
}

可能是VS的BUG 你重新打开个VS把代码复制上去试试

区别相当大,第一个能运行并完成排序

你的第二个直接一个死循环
while (!p)
{
p = true;
for (int i = 0; i < list.Length - 1; i++)
{
if (list[i] > list[i + 1])
{
tmp = list[i];
list[i] = list[i + 1];
list[i + 1] = tmp;

}
p = false;

}
}
最后你把p赋值为false,whiles时候!p不由成了true了啊,而且i的值在执行for循环的时候每次都会变成1~~~
死循环啊大哥!!!

bool p 这里的p是一个标志 判断本次是否发生了交换 如果交换了 p = false; 否则本次循环没有交换 说明排序已经完成 p=true; 这时退出while循环!! 你后面写的形成了死循环。

应该把P的值写在循环内,因为你跳出循环后P的值又变成了FALSE,所以循环条件一直成立,循环一直执行