簡體   English   中英

氣泡排序功能中出現意外0

[英]Unexpected 0 appear in bubble sort function

我是C語言的新手,目前正在學習編寫冒泡排序的基本功能。 一切似乎都很好,程序的其余部分運行良好。 但是,輸出中出現意外的0。 我檢查了我的代碼,但不知道為什么。 有人可以幫我嗎? 輸入和輸出樣本:

The orginal number set is:   23   12   17    8    5   46   75   19   11    4
The sorted number set is:  0  4  5  8 11 12 17 19 23 46

代碼是:

// wirte a program of bubble sort

#include <stdio.h>
#include <string.h>

int main(void)
{
    int num[10];    // a set to store10 numbers
    int temp;   //a temporary variable
    int i,r,t,p,d;  //counters
    //store 10 numbers 
    for(i=0; i<10;++i)
    {
        printf("\nPlease enter the %dth number.\n",i+1);
        scanf("%d",&num[i]);
    }
    printf("\n");
    //display 10 numbers
    printf("The orginal number set is:");
    for(r=0; r<10; ++r)
    {
        printf("%5d",num[r]);    
    }
    printf("\n");
    //start to sort these numbers
    for (p=0;p<10;++p)    
    {
        for(t=0;t<10;++t)
        {
            if(num[t]>num[t+1])
            {
                temp=num[t];
                num[t]=num[t+1];
                num[t+1]=temp;
            } 
        } 
    }
    //print out the sorted set
    printf("The sorted number set is:");
    for(d=0;d<10;++d)
    {
        printf("%3d",num[d]);
    }
    printf("\n");
}

比較值時。 您還將比較最后一個與數組外部的第一個。 這恰好是0(不確定的行為,完全取決於編譯器)並被切入。for循環應為:

for (p=0;p<10;++p)    
{
    for(t=0;t<9;++t)
    {
        if(num[t]>num[t+1])
        {
            temp=num[t];
            num[t]=num[t+1];
            num[t+1]=temp;
        } 
    } 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM