Bubble sort неправильно сортирует массив в c - PullRequest
0 голосов
/ 20 января 2019

Я пытаюсь написать программу для своего класса 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');

}

1 Ответ

0 голосов
/ 20 января 2019

Bubble sort неправильно сортирует массив в 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 не используется внутри внутреннего для , где вы всегда делаете одно и то же независимо от него.Кроме того, вы идете на 1 индекс после последнего

. В SO существует множество реализаций пузырьковой сортировки. Я позволю вам найти и исправить

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;

и avgSum и avg должно быть double


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

mustбыть

while ((switchInput != 'q') && (switchInput != 'Q'));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...