【问题标题】:Bubble sort is not sorting array properly in c冒泡排序未在 c 中正确排序数组
【发布时间】:2019-01-20 08:23:45
【问题描述】:

我正在尝试为我的 C 类编写一个程序来跟踪银行存款。它为您提供了一个菜单,其中包含输入存款的选项、显示所有存款的总和、从最高到最低的存款(使用冒泡排序)、显示平均存款、显示最低存款,然后是退出选项.据我所知,输入、总和和退出选项工作得很好,但其他三个选项都坏了。当你选择它们时,无论你对数组做了什么输入,它的作用就像它们都等于零。这是我到目前为止所拥有的:

#include <stdlib.h>
#include <stdio.h>



int main()

{
    int sortCount, sortCount2, sortCount3, swap;// variables for sort
    int depositCount = 0, sumCount, lowestCount;
    int averageCount, avgSum = 0, avg; //variables for average
    char switchInput = 0;//menu input
    double deposits[100] = { 0 }, sum = 0, average;

    do 
    {
        printf("BANKING MAIN MENU\n\n");
        printf("[M]ake a new deposit\n");
        printf("[S]um of all deposits\n");
        printf("[D]eposits will be displayed from highest to lowest\n");
        printf("[A]verage of all deposits\n");
        printf("[L]owest deposit will be displayed\n");
        printf("[Q]uit\n\n");
        printf("Please enter selection:\n\n");
        scanf(" %c", &switchInput);

        switch (switchInput)
        {
        case 'm': case 'M'://Deposit screen

            printf("\nPlease enter deposit:\n\n");
                scanf("%lf", &deposits[depositCount++]);//deposit input
                ;

            for (sortCount = 0; sortCount < depositCount; sortCount++)//Should sort the array highest to lowest
                for (sortCount2 = 0; sortCount2 < depositCount - sortCount - 1; sortCount2++)
                    if (deposits[sortCount] < deposits[sortCount+1])
                    {
                        swap = deposits[sortCount];
                        deposits[sortCount] = deposits[sortCount+1];
                        deposits[sortCount+1] = swap;
                    }

                break;

        case 's': case 'S'://Total of deposits screen

            for (sumCount = 0; sumCount < depositCount; sumCount++)//depositCount should have it only use parts of the array where there are inputs.
                sum = sum + deposits[sumCount];
                printf("\nYour total deposits equal $%.2lf\n\n", sum);

                break;

        case 'd': case 'D'://Highest to lowest screen


            for (sortCount3 = 0; sortCount3 < depositCount; sortCount3++)//depositCount should have it only use parts of the array where there are inputs.
            {
                printf("$%d \n", deposits[sortCount3]);
            }
            break;

        case 'a': case 'A'://Average screen

            for (sumCount = 0; sumCount < depositCount; sumCount++) //depositCount should have it only use parts of the array where there are inputs.
        {
                avgSum = avgSum + deposits[sumCount];
                avg = avgSum / depositCount;
            }
            printf("Your average deposit is $%.2lf.\n", avg);
            break;

        case 'l': case 'L'://Lowest screen

            printf("The lowest deposit is $%.2lf.\n", deposits[depositCount]);//If the numbers are ordered from highest to lowest, the then entry in the array at the position equal to the number of deposits should be the lowest

            break;

        case 'q': case 'Q'://quit screen

            printf("\nThank you for using our bank!\n\n");
            system("pause");

            return 0;
            break;

        default ://invalid option

            printf("\nInvalid selection!\n\n");
        }

    } while (switchInput != 'q'||'Q');

}

【问题讨论】:

  • 贴出的代码编译不干净!编译时,始终启用警告,然后修复这些警告。 (对于gcc,至少使用:-Wall -Wextra -Wcnversion -pedantic -std=gnu11)注意:其他编译器使用不同的选项来产生相同的结果
  • 关于:} while (switchInput != 'q'||'Q'); 在 C 中,一次只能检查一件事。所以最好写成:} while (switchInput != 'q'|| switchInput == 'Q'); 更好的方法是使用头文件中的tolower()ctype.h 然后写:} while ( tolower( switchInput ) != 'q' ););
  • 冒泡排序不适用于for-loops。请谷歌“冒泡排序”。
  • @PaulOgilvie 你是什么意思?冒泡排序基本上是一个 for 嵌套在另一个
  • @user3629249 必须是 } while (switchInput != 'q' &amp;&amp; switchInput != 'Q'); ^^

标签: c arrays switch-statement average bubble-sort


【解决方案1】:

冒泡排序在 c 中没有正确排序数组

      for (sortCount = 0; sortCount < depositCount; sortCount++)//Should sort the array highest to lowest
           for (sortCount2 = 0; sortCount2 < depositCount - sortCount - 1; sortCount2++)
               if (deposits[sortCount] < deposits[sortCount+1])
               {
                   swap = deposits[sortCount];
                   deposits[sortCount] = deposits[sortCount+1];
                   deposits[sortCount+1] = swap;
               }

sortCount2 在内部 for 中未使用,您总是独立于它做同样的事情。此外,您在最后一个索引之后进入 1 个索引

在 S.O. 上有很多冒泡排序的实现。我让你搜索改正

swap 必须是 double


case 'a': case 'A'://Average screen
       for (sumCount = 0; sumCount < depositCount; sumCount++) //depositCount should have it only use parts of the array where there are inputs.
   {
           avgSum = avgSum + deposits[sumCount];
           avg = avgSum / depositCount;
       }

除法必须在 总和之后进行,不是每次都进行,所以

   case 'a': case 'A'://Average screen
        for (sumCount = 0; sumCount < depositCount; sumCount++) //depositCount should have it only use parts of the array where there are inputs.
        {
            avgSum = avgSum + deposits[sumCount];
        }
         avg = avgSum / depositCount;

and avgSumavg 必须是 double


while (switchInput != 'q'||'Q');

必须

while ((switchInput != 'q') && (switchInput != 'Q'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 2016-02-10
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    • 2015-01-27
    相关资源
    最近更新 更多